首页 › Python 3 教程 › 文件读写

文件读写

把数据保存到文件中,程序退出后数据也不会丢失。本节介绍文本文件和二进制文件的读写方法。

打开文件

f = open("notes.txt", "w", encoding="utf-8")
f.write("第一行\n")
f.close()

推荐使用 with 语句,代码块结束时文件会自动关闭,即使中间发生了异常:

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n")
    f.write("第二行\n")

打开模式

模式含义
r只读(默认),文件不存在时报错
w写入,文件存在则清空,不存在则创建
a追加,写入内容添加到文件末尾
x创建新文件,文件已存在时报错
b二进制模式,与上面组合使用,如 rb、wb
+读写模式,如 r+

读取文件

with open("notes.txt", encoding="utf-8") as f:
    content = f.read()          # 读取全部内容

with open("notes.txt", encoding="utf-8") as f:
    lines = f.readlines()       # 读取为列表,每项带换行符

with open("notes.txt", encoding="utf-8") as f:
    for line in f:              # 逐行读取,内存友好
        print(line.rstrip("\n"))

处理大文件时,应当逐行遍历,而不是一次 read() 全部内容。

写入多行

lines = ["苹果", "香蕉", "橙子"]
with open("fruits.txt", "w", encoding="utf-8") as f:
    f.writelines(line + "\n" for line in lines)
    print("葡萄", file=f)      # print 也可以写文件

二进制文件

图片、压缩包等非文本文件使用二进制模式读写,此时不能指定 encoding:

with open("photo.jpg", "rb") as src, open("photo_copy.jpg", "wb") as dst:
    while chunk := src.read(64 * 1024):
        dst.write(chunk)

:= 是 Python 3.8 引入的海象运算符,在表达式中同时完成赋值和判断。

编码问题

完整示例:日志分析

from collections import Counter

log = """2026-11-01 10:00:01 INFO  user login
2026-11-01 10:00:05 ERROR db timeout
2026-11-01 10:01:12 INFO  user logout
2026-11-01 10:02:30 ERROR db timeout
2026-11-01 10:03:00 WARN  disk 85%"""

with open("app.log", "w", encoding="utf-8") as f:
    f.write(log)

levels = Counter()
errors = []
with open("app.log", encoding="utf-8") as f:
    for line in f:
        date, time, level, *msg = line.split()
        levels[level] += 1
        if level == "ERROR":
            errors.append(f"{time} {' '.join(msg)}")

print("各级别数量:", dict(levels))
print("错误明细:", errors)
文件路径的拼接、目录遍历等操作,推荐使用标准库教程中介绍的 pathlib。

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 把 1 到 10 的平方写入文件 squares.txt,每行一个数,然后读取并求和。

查看参考答案
import os, tempfile
path = os.path.join(tempfile.gettempdir(), "squares.txt")
with open(path, "w", encoding="utf-8") as f:
    for i in range(1, 11):
        f.write(f"{i * i}\n")
with open(path, encoding="utf-8") as f:
    print(sum(int(line) for line in f))
os.remove(path)
参考输出:
385

练习 2 统计一个文本文件中最长的一行是第几行、有多少个字符。

查看参考答案
import os, tempfile
path = os.path.join(tempfile.gettempdir(), "demo.txt")
with open(path, "w", encoding="utf-8") as f:
    f.write("短\n这是最长的一行文字\n中等长度\n")
with open(path, encoding="utf-8") as f:
    no, line = max(enumerate(f, 1), key=lambda x: len(x[1].rstrip("\n")))
print(f"第 {no} 行,{len(line.rstrip())} 个字符")
os.remove(path)
参考输出:
第 2 行,9 个字符