如何在 Python 中写入文件(写入和追加)

了解如何使用 Python 将文本写入文件。使用安全上下文管理器掌握写入(“w”)和追加(“a”)模式之间的区别。

在编辑器中尝试此解决方案

概述

将数据写入文件是构建脚本、保存程序状态、创建日志或导出报告时的一项基本任务。 Python 使用内置的“open()”函数结合控制数据写入磁盘方式的特定文件访问模式来简化文件输出。

写入文件时,两种最常见的模式是写入模式(“w”)和追加模式(“a”)。如果文件已存在,写入模式将完全覆盖该文件;如果不存在,则创建一个新文件。追加模式保留现有内容并直接在文件末尾写入新数据。使用错误的模式可能会导致数据意外丢失,因此请谨慎选择。

与读取文件类似,您应该始终使用“with open(...)”语句。这可确保刷新文件缓冲区并正确关闭文件句柄,从而节省系统资源并防止数据损坏。为了写入字符串列表,Python 提供了 .writelines() 方法,使批量写入变得干净高效。

代码和执行输出

该脚本演示了在 Python 中覆盖、追加和查看文件。

# 1. Overwrite a file (or create new) using "w"
with open("output.txt", "w") as file:
    file.write("Hello World from Python!\n")
    file.write("Writing file content is simple.\n")

# 2. Append new content to the file using "a"
with open("output.txt", "a") as file:
    file.write("This line is appended.\n")

# 3. Reading the file back to verify contents
with open("output.txt", "r") as file:
    print(file.read().strip())
端子输出
Hello World from Python!
Writing file content is simple.
This line is appended.

逐步实施

  • 使用 with open('filename', 'w') as file 来覆盖或创建文件。
  • 使用 with open('filename', 'a') as file 在文件末尾附加文本。
  • 调用 file.write('string') 将各个文本段写入文件。

常见问题解答

如果文件的目录不存在会发生什么?

Python 将引发 FileNotFoundError。在写入文件之前,必须先使用 os.makedirs 函数创建目录。

如何将变量或数字写入文件?

write() 方法仅接受字符串参数。您必须使用 str(num) 转换数字或使用 f 字符串格式化它们。

相关主题

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。