Whenever a file is opened using the write flag w, the contents of the file are deleted and opened afresh to write data. There is an alternative flag a that enables appending data to the end of the file. This flag also creates a new file if the file (that is passed as an argument to open) doesn't exist. Let's consider the code snippet below where we append a line to the text file write_file.txt from the previous section:
if __name__ == "__main__":
# open text file to append
file = open('write_file.txt', 'a')
# append a line from the file
file.write('This is a line appended to the file\n')
file.close()
file = open('write_file.txt', 'r')
data = file.read()
print(data)
file.close()
When the preceding code snippet is executed (available for download along with this chapter—append_to_file.py), the string This is a line appended to the file is appended to the end of the text of the file. The contents of the file will include the following:
I am excited to learn Python using Raspberry Pi Zero
This is a line appended to the file