How to Append String into File in Python


In this example we will show how to get a string from the user and append the string into the current file in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
tr = input("Please input the string: ")
with open(fileName, 'a') as file:
    file.write("\n")
    file.write(str)
print("After appending, the content of the file: ")
with open(fileName, 'r') as file:
    for line in file:
        print(line, end="")
Content of test1.txt:
Python is an easy to learn
powerful programming language

Output:

Enter the name of the file with .txt extension: test1.txt
Please input the string: Hello Python
After appending, the content of the file: 
Python is an easy to learn
powerful programming language
Hello Python
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments