KDnuggets

Python 文件写入指南:初学者教程

5.5内容质量
Python 文件写入指南:初学者教程

TL;DR · AI 摘要

Python 通过 open() 函数和 with 上下文管理器实现文件写入,核心在于根据需求选择 w(覆盖)、a(追加)或 x(排他性创建)模式以确保数据存储的正确性。

核心要点

  • 应优先使用 with open() 语法而非手动 close(),以确保在发生异常时文件能被正确关闭。
  • 写入模式 w 会覆盖原文件,a 模式在文件末尾追加内容,x 模式则在文件已存在时抛出 FileExistsError。
  • 使用 writelines() 写入列表时必须手动在字符串末尾添加 \n 换行符,否则内容将全部连接在同一行。

结构提纲

按章节快速跳转。

  1. 使用 open() 函数配合 'w' 模式可以创建新文件或覆盖现有文件内容。

  2. with open() 结构是 Python 的最佳实践,因为它能自动处理文件的关闭操作。

  3. 通过 w (写入)、a (追加)、x (创建) 和 r (读取) 四种模式控制对文件的访问行为。

  4. 利用 \n 换行符或 writelines() 方法可以将多条记录高效地写入文本文件。

  5. 使用 'a' 模式保存日志记录,使用 'x' 模式防止意外覆盖已有文件。

思维导图

用一张图看清主题之间的关系。

查看大纲文本(无障碍 / 无 JS 友好)
  • Python 文件写入
    • 写入方式
      • open() + close()
      • with open() (推荐)
    • 文件模式
      • w: 覆盖写入
      • a: 末尾追加
      • x: 排他创建
      • r: 只读
    • 写入方法
      • write(): 单条写入
      • writelines(): 列表写入

金句 / Highlights

值得收藏与分享的关键句。

  • 推荐使用 with open(),因为它在代码块结束后会自动关闭文件。

    Using with open(): The Better Way

    ⬇︎ 下载 PNG𝕏 分享到 X
  • 当你想要创建新文件或替换现有内容时使用 'w';当你想要在文件末尾添加新内容时使用 'a'。

    Understanding File Modes

    ⬇︎ 下载 PNG𝕏 分享到 X
  • writelines() 不会自动添加换行符,你需要手动包含 \n。

    Writing Multiple Lines

    ⬇︎ 下载 PNG𝕏 分享到 X
#Python#文件 I/O#编程入门
打开原文
Image 1: How to Write to Files in Python: A Beginner's Guide
Image 1: How to Write to Files in Python: A Beginner's Guide

#介绍

写文件是 Python 的一项基本技能。它可以让你将数据永久保存,而不是在程序停止时丢失。你可以利用文件保存来存储结果、日志、报告、用户输入、设置以及结构化数据。

在本指南中,你将学习如何创建文本文件、写入多行、追加内容、处理文件夹,以及以 CSV 和 JSON 格式保存数据。你还会了解最常用的文件模式,包括 waxr,以及何时使用每一种。

到最后,你将能够编写 Python 程序,将结果、报告、日志和结构化数据保存到文件中。

#写入第一个文本文件

最简单的写文件方式是使用 Python 内置的 open() 函数。

w 模式表示写入模式。若文件不存在,Python 会创建它;若文件已存在,Python 会覆盖其原有内容。

python
file = open("message.txt", "w")
file.write("Hello, this is my first file written with Python.")
file.close()

运行上述代码后,Python 会在与你的 notebook 或脚本相同的文件夹中创建一个名为 message.txt 的文件。

你可以再次读取文件来检查保存的内容。

python
file = open("message.txt", "r")
content = file.read()
file.close()

print(content)

输出:

code
Hello, this is my first file written with Python.

#使用 `with open()`: 更好的方式

虽然可以手动打开和关闭文件,但推荐的做法是使用 with open()

它会在代码块结束后自动关闭文件,代码更简洁、更安全,也更符合实际项目的惯例。

python
with open("message.txt", "w") as file:
    file.write("This file was written using with open().")

with open("message.txt", "r") as file:
    content = file.read()

print(content)

输出:

code
This file was written using with open().

使用 with open() 是最佳实践,因为你不必记得手动关闭文件。

#理解文件模式

打开文件时,模式告诉 Python 你想对文件做什么。

| 模式 | 含义 | | --- | --- | | w | 写入文件。创建新文件或覆盖已有文件。 | | a | 追加到文件。将内容添加到末尾,不删除已有内容。 | | x | 创建新文件。若文件已存在则失败。 | | r | 读取文件。若文件不存在则失败。 |

写文件时最常用的模式是 wa。当你想创建新文件或替换已有内容时使用 w;当你想在文件末尾添加新内容时使用 a

#写入多行

你可以通过添加换行符 \n 来写入多行。

python
with open("notes.txt", "w") as file:
    file.write("Line 1: Learn Python\n")
    file.write("Line 2: Practice file handling\n")
    file.write("Line 3: Build small projects\n")

读取文件:

python
with open("notes.txt", "r") as file:
    print(file.read())

输出:

code
Line 1: Learn Python
Line 2: Practice file handling
Line 3: Build small projects

你也可以使用 writelines() 一次写入字符串列表。

python
tasks = [
    "Write Python code\n",
    "Run the notebook\n",
    "Check the output file\n"
]

with open("tasks.txt", "w") as file:
    file.writelines(tasks)

读取文件:

python
with open("tasks.txt", "r") as file:
    print(file.read())

输出:

code
Write Python code
Run the notebook
Check the output file

需要注意的是,writelines() 并不会自动添加换行符,你需要自行在字符串中包含 \n

#追加到文件

有时你不想替换文件中的已有内容,而是想在末尾添加新内容。

这时使用追加模式 a

python
with open("journal.txt", "w") as file:
    file.write("Day 1: I started learning Python file handling.\n")

with open("journal.txt", "a") as file:
    file.write("Day 2: I learned how to append text to a file.\n")

读取文件:

python
with open("journal.txt", "r") as file:
    print(file.read())

输出:

code
Day 1: I started learning Python file handling.
Day 2: I learned how to append text to a file.

追加模式在处理日志、日记、报告或任何需要持续添加新信息的文件时非常有用。

#安全创建文件

如果你想创建新文件但避免覆盖已有文件,使用 x 模式。

此模式仅在文件不存在时创建文件;若文件已存在,Python 会抛出 FileExistsError

python
try:
    with open("new_file.txt", "x") as file:
        file.write("This file was created using x mode.")
    print("File created successfully.")
except FileExistsError:
    print("The file already exists, so Python did not overwrite it.")

若文件不存在,你会看到:

code
File created successfully.

若文件已存在,你会看到:

code
The file already exists, so Python did not overwrite it.

这在你想保护已有文件不被意外覆盖时非常有用。

#处理文件路径

默认情况下,Python 会将文件保存在 notebook 或脚本所在的同一文件夹中。

如果你想将文件保存在特定文件夹内,可以使用 [pathlib](https://docs.python.org/3/library/pathlib.html)

python
from pathlib import Path

output_folder = Path("output")
output_folder.mkdir(exist_ok=True)

file_path = output_folder / "summary.txt"

with open(file_path, "w") as file:
    file.write("This file was saved inside the output folder.")

print(f"File saved to: {file_path}")

输出:

File saved to: output/summary.txt

现在读取文件:

code
with open("output/summary.txt", "r") as file:
    print(file.read())

输出:

This file was saved inside the output folder.

mkdir(exist_ok=True) 调用会在文件夹不存在时创建它。如果文件夹已经存在,Python 不会抛出错误。

#写 CSV 文件

CSV 文件非常适合保存表格数据,例如行和列。它们通常在 Excel 或 Google Sheets 等电子表格工具中打开。

在 Python 中写 CSV 文件,使用 [csv](https://docs.python.org/3/library/csv.html) 模块。

code
import csv

students = [
    ["Name", "Score"],
    ["Ayesha", 92],
    ["Bilal", 85],
    ["Sara", 88]
]

with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(students)

读取 CSV 文件:

code
with open("students.csv", "r") as file:
    print(file.read())

输出:

code
Name,Score
Ayesha,92
Bilal,85
Sara,88

newline="" 参数有助于避免在 Windows 上写 CSV 文件时出现额外的空行。

#写 JSON 文件

JSON 是另一种常见的结构化数据存储格式。它常用于字典、API 响应、配置文件和嵌套数据。

在 Python 中写 JSON 文件,使用 [json](https://docs.python.org/3/library/json.html) 模块。

code
import json

profile = {
    "name": "Ayesha",
    "role": "Data Analyst",
    "skills": ["Python", "SQL", "Excel"],
    "active": True
}

with open("profile.json", "w") as file:
    json.dump(profile, file, indent=4)

读取 JSON 文件:

code
with open("profile.json", "r") as file:
    print(file.read())

输出:

code
{
    "name": "Ayesha",
    "role": "Data Analyst",
    "skills": [
        "Python",
        "SQL",
        "Excel"
    ],
    "active": true
}

indent=4 参数让 JSON 文件更易读。

#常见初学者错误

以下是初学者在 Python 写文件时常犯的一些错误。

| 错误 | 结果 | 解决办法 | | --- | --- | --- | | 忘记关闭文件 | 更改可能不会正确保存 | 使用 with open() | | 用 w 而不是 a | 现有内容被删除 | 追加时使用 a | | 忘记 \n | 文本显示在同一行 | 添加换行符 | | 写入不存在的文件夹 | Python 抛出错误 | 先创建文件夹 | | 直接写非字符串数据 | Python 可能抛出 TypeError | 将值转换为字符串或使用 CSV/JSON |

#总结

写文件是最实用的初学者 Python 技能之一。我仍记得在大二时参加编程竞赛,几乎花了一小时试图弄清楚如何保存文件。如果我早知道这么简单,我可能会赢得比赛。

文件保存可以让你存储日志、保存程序输出、创建报告、保存用户数据,甚至使用 JSON 等格式读写简单数据库。最棒的是,Python 的文件处理是原生、快速且开箱即用的。

对于大多数任务,使用 with open(),它会自动为你关闭文件。使用 w 写入或覆盖文件,使用 a 追加新内容,使用 x 安全创建新文件而不覆盖已有文件。

[](https://abid.work/)**[Abid Ali Awan](https://abid.work/)** (@1abidaliawan) 是一名认证数据科学专业人士,热衷于构建机器学习模型。目前他专注于内容创作和撰写关于机器学习与数据科学技术的技术博客。Abid 拥有技术管理硕士学位和电信工程学士学位。他的愿景是为患有心理疾病的学生打造一款基于图神经网络的 AI 产品。