Appending to a file

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 ...

Get Python Programming with Raspberry Pi now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.