How to open a file in append mode in Python?

Published on Aug. 22, 2023, 12:19 p.m.

To open a file in append mode in Python, you can use the ‘a’ mode argument when opening the file. Here is an example:

with open('example.txt', 'a') as file:
    file.write('This text will be appended to the end of the file.\n')

In this example, we used the open() function with the ‘a’ mode argument to open a file named ‘example.txt’ in append mode. We then used the write() method of the file object to append some text to the end of the file.

Note that when you open a file in append mode, the file pointer is positioned at the end of the file, so any data you write to the file will be appended to the existing data. Also, if the file doesn’t exist, it will be created.

You can also use the ‘a+’ mode argument if you want to open the file for both reading and appending. In this mode, the file pointer is positioned at the end of the file for writing, but it is positioned at the beginning of the file for reading.

Tags: