with open:标准姿势

永远用 with,会自动关文件:

with open("hello.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n")
    f.write("第二行\n")
# 出 with 块自动关闭,即使报错也会关

三种打开模式

模式 含义
"r" 读(默认)。文件不存在会报错
"w" 写。会清空原内容!文件不存在则创建
"a" 追加。在文件末尾继续写
"r+" 读写
"b" b 表示二进制(如 "rb" "wb"

读:一次读完 vs 逐行读

# 一次读全部到字符串
with open("data.txt", encoding="utf-8") as f:
    text = f.read()

# 一次读一行
with open("data.txt", encoding="utf-8") as f:
    first = f.readline()

# 读所有行成列表
with open("data.txt", encoding="utf-8") as f:
    lines = f.readlines()    # ['line1\n', 'line2\n', ...]

# 推荐:迭代(内存友好)
with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())    # rstrip 去掉行尾换行

写:一次写 vs 多行

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("一行内容\n")
    f.writelines(["a\n", "b\n", "c\n"])

writelines 不会自动加换行,所以列表项要自己带 \n

encoding 一定要写

中文环境必须明确指定 encoding="utf-8"

# Windows 默认是 GBK,读 UTF-8 中文文件会乱码
with open("中文.txt", encoding="utf-8") as f:
    print(f.read())

二进制模式:图片 / PDF / 任何非文本

with open("image.png", "rb") as f:
    data = f.read()       # bytes 类型,不是 str

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

不要给二进制模式加 encoding——会报错。

JSON 文件(常见场景)

import json

# 写
data = {"name": "WadeLy", "age": 30}
with open("user.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 读
with open("user.json", encoding="utf-8") as f:
    data = json.load(f)

ensure_ascii=False 让中文不被转成 \uXXXX

下一篇讲异常处理——文件不存在 / 数字转换失败 怎么办。