深度阅读

How to append text to a file in Python

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

To append text to a file in Python, you can use the open() function in “append” mode, which is denoted by “a” as the second argument. Here is an example:

with open("file.txt", "a") as file:
    file.write("This is a new line.")

In the example above, the “with” statement ensures that the file is properly closed after the write operation is completed. The “a” mode ensures that the text is appended to the end of the file, without overwriting any existing content. You can replace “file.txt” with the name of the file you want to append text to.

Note that if the file does not exist, it will be created automatically when you open it in “append” mode.

博客作者

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