跳转至

文件操作

文件操作是程序与外部世界交互的重要方式。Python 提供了内置的 open() 函数来处理文件,建议配合 ospathlib 模块使用。

1. 打开文件

open() 函数

file = open("filename.txt", mode="r", encoding="utf-8")
# ... 操作文件 ...
file.close()  # 必须记得关闭!

文件模式 (Mode)

模式 描述 注意
'r' 只读 (Read) 默认模式。文件不存在会报错。
'w' 写入 (Write) 文件存在则清空重写,不存在则创建。
'a' 追加 (Append) 在文件末尾追加。不存在则创建。
'x' 独占创建 创建新文件,如果文件已存在则报错。
'b' 二进制 (Binary) 图片、音频等非文本文件 (如 'rb', 'wb')。

2. 上下文管理器 (with 语句)

这是 Python 文件操作的最佳实践。 with 语句会在代码块执行完毕后(即使发生异常)自动关闭文件,无需手动调用 close()

# ✅ 推荐写法
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("Hello World")

# 离开缩进块后,文件已自动关闭

3. 读取文件

假设 data.txt 内容如下:

Line 1: Python
Line 2: Java
Line 3: C++

方法 1: read() - 读取全部

with open("data.txt", "r") as f:
    content = f.read()  # 读取整个文件为字符串
    print(content)

方法 2: readline() - 逐行读取

with open("data.txt", "r") as f:
    print(f.readline()) # 读取第一行
    print(f.readline()) # 读取第二行

方法 3: readlines() - 读取列表

with open("data.txt", "r") as f:
    lines = f.readlines() # 返回列表 ['Line 1...\n', 'Line 2...\n']

for line in lines:
    print(line.strip()) # strip() 去除末尾的换行符

方法 4: 直接遍历文件对象 (最常用)

内存最高效的方式,适合读取大文件。

with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

4. 写入文件

lines = ["First Line\n", "Second Line\n"]

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Header\n")      # 写入单个字符串
    f.writelines(lines)      # 写入字符串列表

5. 文件路径处理 (pathlib)

Python 3.4+ 引入了 pathlib 模块,提供了面向对象的文件路径操作,比传统的 os.path 更好用。

from pathlib import Path

# 定义路径
p = Path("docs/data") / "test.txt"  # 使用 / 拼接路径

# 检查是否存在
if not p.exists():
    print("文件不存在")

# 创建目录 (mkdir -p)
p.parent.mkdir(parents=True, exist_ok=True)

# 快捷读写文本
p.write_text("Hello Pathlib", encoding="utf-8")
print(p.read_text(encoding="utf-8"))

# 获取文件信息
print(p.name)       # test.txt
print(p.suffix)     # .txt
print(p.stem)       # test

6. 二进制文件 (图片/视频)

读取图片并复制:

with open("image.png", "rb") as source_file:
    data = source_file.read()

with open("copy.png", "wb") as dest_file:
    dest_file.write(data)

本章小结

  • 始终使用 with open(...) 来自动管理文件关闭。
  • 如果是文本文件,记得指定 encoding='utf-8' 以防乱码。
  • 读取大文件时,直接用 for line in f: 遍历。
  • 使用 pathlib 处理文件路径和目录操作。

练习题

  1. 日志写入:编写一个程序,每次运行都将当前的时间 (使用 datetime 模块) 追加写入到 log.txt 文件中。
  2. 文本统计:读取一个英文文本文件,统计其中单词 "Python" 出现的次数。
  3. 文件复制:编写一个 copy_file(src, dst) 函数,实现文件的复制功能。

下一章:错误与异常处理