Python 文件操作

Python 的文件操作可以概括为一句话:
“一切皆对象,用 with 管资源”


一、最核心的 3 件事

1️⃣ open() 打开文件
2️⃣ read / write 操作内容
3️⃣ close() 释放资源(或用 with 自动做)


二、打开文件:open()

f = open("test.txt", "r")

常用打开模式(非常重要)

模式 含义
"r" 读(默认,文件必须存在)
"w" 写(不存在则创建,存在则清空)
"a" 追加
"x" 新建(存在就报错)
"b" 二进制
"t" 文本(默认)

组合使用:

"rb"   # 读二进制
"wb"   # 写二进制
"r+"   # 读写

三、强烈推荐:with 语法(自动关文件)

❌ 不推荐

f = open("test.txt", "r")
data = f.read()
f.close()

✅ 推荐(工程标准)

with open("test.txt", "r", encoding="utf-8") as f:
    data = f.read()

👉 异常也能自动 close,和 Java try-with-resources 一个意思


四、读文件的 3 种方式

1️⃣ 一次性读(小文件)

with open("test.txt") as f:
    content = f.read()

2️⃣ 按行读(最常用)

with open("test.txt") as f:
    for line in f:
        print(line.strip())

👉 大文件首选,不占内存


3️⃣ 读成列表

with open("test.txt") as f:
    lines = f.readlines()

五、写文件

1️⃣ 覆盖写

with open("test.txt", "w") as f:
    f.write("hello\n")

2️⃣ 追加写

with open("test.txt", "a") as f:
    f.write("new line\n")

3️⃣ 写多行

lines = ["a\n", "b\n", "c\n"]

with open("test.txt", "w") as f:
    f.writelines(lines)

六、二进制文件(图片 / 音频 / PDF)

with open("a.png", "rb") as f:
    data = f.read()

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

👉 下载文件 / 转存文件的底层就是这个


七、文件指针(cursor)

with open("test.txt") as f:
    print(f.tell())   # 当前位置
    f.seek(0)         # 移动指针

一般场景很少用,知道即可。


八、文件 & 目录操作(os / pathlib)

1️⃣ 判断文件是否存在

import os

os.path.exists("test.txt")

2️⃣ 创建目录

os.makedirs("a/b/c", exist_ok=True)

3️⃣ 列出目录文件

os.listdir(".")

4️⃣ 删除文件 / 目录

os.remove("test.txt")
os.rmdir("empty_dir")

5️⃣ 强烈推荐:pathlib(现代写法)

from pathlib import Path

p = Path("test.txt")

p.exists()
p.read_text(encoding="utf-8")
p.write_text("hello", encoding="utf-8")

👉 非常适合工程项目,强烈推荐你用这个


九、几个“工程中极其常见”的文件操作

1️⃣ 读取 JSON 文件

import json

with open("config.json") as f:
    data = json.load(f)

2️⃣ 写 JSON 文件

with open("config.json", "w") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

3️⃣ 读取 CSV

import csv

with open("data.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

4️⃣ 写日志文件

with open("app.log", "a") as f:
    f.write("something happened\n")

十、和你熟悉语言的对照理解

vs Java

  • Python 的 with ≈ Java 的 try-with-resources
  • Python 文件对象 ≈ Java Stream / Reader

vs JavaScript(Node.js)

  • Python 文件 IO 默认同步
  • Node.js 默认异步(callback / promise)

👉 Python 更偏脚本 / 数据 / 自动化


十一、常见坑(一定要知道)

⚠️ 中文乱码:

open("a.txt", encoding="utf-8")

⚠️ 写文件把内容清空了:

  • 用了 "w" 而不是 "a"

⚠️ 大文件一次性 read()

  • 可能 OOM

十二、一句话总结

Python 文件操作 = open + with + 正确的模式

在工程中:

  • 80% 用 with open(...)
  • 10% 用二进制
  • 10% 用 pathlib
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐