Python Program to Append Text to a File

In this article, you will learn and get code to append some content (text) into a file using a Python program. Here are the list of programs:

Things to do Before Program

Because the program given below appends text (string or content) entered by user to a file say fresherearth.txt. Therefore before executing the program, we've to create a file named fresherearth.txt with some content say:

Hello Python,
I'm a File
My Name is fresherearth.txt

Save this file in the current directory. The current directory means the directory where you are saving your Python source code. That is, the file and the Python program (to append text to the file) must be available in the same folder. Here is the snapshot of the folder where we've saved this file:

python append text to file

And here is the snapshot of opened file, fresherearth.txt:

append content to file python

Now let's create a python program to append new content at last of this file.

Append Text to a File in Python

This Python program asks from user to enter the name of file and then asks to enter the text (in one or more lines) to append it to the given file as shown in the program given here:

print("Enter the Name of File: ")
fileName = str(input())
fileHandle = open(fileName, "a")
print("Enter the Text to Append in Given File: ")
while True:
    text = str(input())
    if len(text)>0:
        fileHandle.write("\n")
        fileHandle.write(text)
    else:
        break
fileHandle.close()

Here is its sample run:

python program append text to file

Now enter the name of file say fresherearth.txt and press ENTER. Here is the output you will see:

append text to file python

Then enter some texts (contents) say:

These three lines entered in a way that, enter the first line of text, then press ENTER, again enter second line of text, press ENTER key and so on. Finally press ENTER key without typing anything to stop appending the content in the file. Here is the sample run with exactly same user inputs (as given above):

append content to text file python

Now if you open the same file, fresherearth.txt, then these content gets appended (added) to the file. Here is the snapshot of the opened file, fresherearth.txt:

python append content to file

Note - The open() function is used to open a file. It returns a file object. It takes two arguments. The first argument is the name of file and the second argument is its opening mode.

Note - The break keyword is used (in above program) to exit from the while loop

Note - The write() function is used to write content to a file using its object say fileHandle

Note - Don't forgot to close the file's object using close() function

Append Text to File and Display the File

This program is similar to previous program with an extra feature. The extra feature is, this program appends the content entered by user to the given file and then asks from user whether they wants to see the new content of file or not.

print(end="Enter the Name of File: ")
fileName = str(input())
try:
    fileHandle = open(fileName, "r")
    print("This File is Available!")
    fileHandle.close()
    fileHandle = open(fileName, "a")
    print(end="\nEnter Texts to Append: ")
    while True:
        text = str(input())
        if len(text)>0:
            fileHandle.write("\n")
            fileHandle.write(text)
        else:
            break
    fileHandle.close()
    print("Texts Appended to the File Successfully!")
    print(end="Want to see the Content of File (y/n): ")
    ch = input()
    if ch=='y':
        fileHandle = open(fileName, "r")
        for content in fileHandle:
            print(end=content)
    else:
        print("Exiting...")
except IOError:
    try:
        fileHandle = open(fileName, "a")
        print("File Created Successfully!")
        print(end="\nEnter Texts to Append (Add): ")
        while True:
            text = str(input())
            if len(text)>0:
                fileHandle.write(text)
                fileHandle.write("\n")
            else:
                break
        fileHandle.close()
        print("Texts Appended to the File Successfully!")
        print(end="Want to see the Content of File (y/n): ")
        ch = input()
        if ch=='y':
            fileHandle = open(fileName, "r")
            for content in fileHandle:
                print(end=content)
        else:
            print("Exiting...")
    except IOError:
        print("Error Occurred!")
print()

Now enter the name of same file, that is fresherearth.txt and press ENTER. Here is the output:

python program append to file

Enter the following text, one by one:

Supply exactly these inputs and press ENTER key without typing any text. Here is the output you will see:

append to file python program

Now type y and press ENTER key to see the content of the file, fresherearth.txt. Otherwise press n to exit from the program. Here is the sample output with y as choice:

append with new line python

And here is the file, fresherearth.txt after executing all the things given above:

python append text with newline

Here is another sample run with user input say fresherearth.html, the file that doesn't exist in the current directory, with some content and then y as choice to see the content of file:

python program append content to file

Note - The a (append) file opening mode opens a file. If file doesn't exist, then a new file with same name gets created automatically.

Now if you open this newly created file say fresherearth.html through previous program's sample run, in a web browser like Google Chrome, here is the output you will see:

append to html file python

Note - Because the file is of HTML type, therefore this output is produced. To learn more about it, refer to HTML Tutorial to get its in-depth detail.

Python Online Test


« Previous Program Next Program »