How to keep old content when Writing to Files in Python?

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

To keep the old content when writing to files in Python, you can use the “append” mode instead of “write” mode when opening the file. This will allow you to add new content to the end of the file without overwriting the existing content.

Here’s an example:

with open('myfile.txt', 'a') as f:
    f.write('New content\n')

In this example, we open the file ‘myfile.txt’ in “append” mode using the with statement. Then, we use f.write() to add new content to the end of the file. The new content will be added after the existing content, so the old content will be preserved.

Note that if you want to overwrite part of the file, you will need to use “read” mode to read in the existing content, modify it as needed, and then use “write” mode to write the modified content back to the file. Alternatively, if you want to replace the entire file with new content, you can use “write” mode, but this will overwrite the existing content.

Tags: