深度阅读

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

作者
作者
2023年08月22日
更新时间
9.52 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。