Append Data to a File in Python Programming

Append data to a File: When file is opened in write mode then cursor at starting index. That’s why if we start writing file in write mode then it starts to write file from beginning and over write the existing data in file.

But in append() ie. “a” mode, the cursor placed at the last index always. Due to this, if we start writing data to file in append mode then it start to writing file from last instead of over writing existing file.

python-video-tutorials

Syntax: Suppose we already have a file “Abc.txt” with data written “I love Python”. Let’s perform append operation on that file.

#www.pythonlobby.com
f = open("Abc.txt",'a')
f.write(" Programming")
f.close()

Output:

#I love Python Programming

Hence, you can observe that it append the text “Programming” at the end and did not overridden the old data.

writelines-in-python

Important:

1). File access mode ‘a’ is used for appending data in a file.
2). Always call close() function after performing operation on file to commit changes.
3). Append mode in file handling is the useful method to solve overridden problem arising while writing data to file using write() and writelines() method.

Example 1: I already have a file named “test.txt” and data already written in file is “Hello”. Below example demonstrate the code of appending word “Everyone” to the existing data in file.

appending-data-to-file-in-python

Output: Data written to file is

appending-data-to-file-in-python-2

So, this is all about the appending data to a file.