January 1, 2024

Python Program to Append to a File

In the post Python Program to Write a File we saw options to write to a file in Python but that has the drawback of overwriting the existing file. If you want to keep adding content to an existing file you should use append mode to open a file. In this tutorial we’ll see options to append to a file in Python.

Append mode in Python I/O

To append data to a file i.e. adding content to the end of an existing file you should open file in append mode (‘a’). If the file doesn’t exist it will create a new file for writing content.

Appending to a file in Python

Following method opens the passed file in append mode in Python and then adds content to the end of the file.

def append_file(fname):
  with open(fname, 'a') as f:
    f.write('This line is added to the already existing content')

Using ‘a+’ mode to write and read file

Following program opens a file in ‘a+’ mode for both appending and reading. Program also uses tell() method to get the current position of the file pointer and seek() method to move to the beginning of the file.

def append_file(fname):
  with open(fname, 'a+') as f:
    f.write('This line is added to the already existing content')
    f.flush()
    print("Current position of file pointer- ", f.tell())
    f.seek(0, 0)
    s = f.read()
    print('Content- ', s)

That's all for the topic Python Program to Append to a File. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment