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.
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.
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.
Output: Data written to file is
So, this is all about the appending data to a file.