Python 的文件 I/O 操作是数据处理的基础技能,涉及文件的读写、路径管理、异常处理等核心功能。以下是文件 I/O 的核心知识点:
一、基础文件操作
1. 打开文件
# 通用模式:r(读)/w(写)/a(追加) + b(二进制)/t(文本,默认)
f = open("data.txt", "r", encoding="utf-8") # 文本模式读取
f = open("image.jpg", "rb") # 二进制模式读取
2. 关闭文件
f.close() # 显式关闭(需确保执行)
# 推荐方式:使用 with 语句自动关闭
with open("data.txt", "r") as f:
content = f.read()
# 此时文件已自动关闭
二、文件读写模式
模式 | 描述 | 行为 |
---|---|---|
r | 读取(默认) | 文件必须存在 |
w | 写入 | 覆盖已存在文件,不存在则创建 |
a | 追加 | 文件末尾写入,不存在则创建 |
r+ | 读写 | 文件必须存在 |
w+ | 读写 | 覆盖已存在文件,不存在则创建 |
b | 二进制模式 | 与其他模式组合使用(如 rb ) |
三、文件内容操作
1. 读取内容
with open("data.txt", "r") as f:
# 读取全部内容
full_text = f.read()
# 逐行读取(生成器)
for line in f:
print(line.strip())
# 读取指定大小
chunk = f.read(1024) # 读取1KB
2. 写入内容
with open("output.txt", "w") as f:
f.write("Hello, World!\n") # 写入字符串
f.writelines(["Line1\n", "Line2\n"]) # 写入多行
四、文件路径处理
1. 路径操作
import os
# 拼接路径(跨平台安全)
file_path = os.path.join("folder", "subfolder", "file.txt")
# 获取绝对路径
abs_path = os.path.abspath("data.txt")
# 检查文件存在性
if os.path.exists("data.txt"):
print("文件存在")
2. 路径分解
path = "/user/docs/report.pdf"
print(os.path.basename(path)) # → "report.pdf"
print(os.path.dirname(path)) # → "/user/docs"
五、高级文件操作
1. 文件指针控制
with open("data.txt", "r+") as f:
f.seek(10) # 移动到第10字节
f.write("X") # 覆盖写入
f.seek(0) # 返回文件开头
print(f.read())
2. 二进制文件处理
# 读取图片文件
with open("image.jpg", "rb") as f:
img_data = f.read()
# 写入二进制数据
with open("copy.jpg", "wb") as f:
f.write(img_data)
3. 临时文件
import tempfile
with tempfile.NamedTemporaryFile(mode="w+t") as tmp:
tmp.write("临时内容")
tmp.seek(0)
print(tmp.read())
# 临时文件自动删除
六、异常处理
try:
with open("missing.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("文件不存在!")
except PermissionError:
print("无访问权限!")
except IOError as e:
print(f"I/O错误: {str(e)}")
七、实用技巧
1. 逐行处理大文件
with open("large_log.txt", "r") as f:
for line in f:
if "ERROR" in line:
print(f"发现错误: {line.strip()}")
2. CSV 文件操作
import csv
# 写入CSV
with open("data.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 30])
# 读取CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
3. JSON 文件操作
import json
data = {"name": "Bob", "age": 25}
# 写入JSON
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# 读取JSON
with open("data.json", "r") as f:
loaded_data = json.load(f)
八、性能优化
-
缓冲区控制:
# 增大缓冲区提升大文件读写性能 with open("data.txt", "r", buffering=65536) as f: pass
-
内存映射文件:
import mmap with open("large_file.bin", "r+b") as f: mm = mmap.mmap(f.fileno(), 0) mm[1024:1028] = b"TEST" # 直接修改内存映射 mm.close()
九、常见陷阱
-
文件未关闭:
# 错误示例:异常导致文件未关闭 f = open("data.txt", "r") # ... 可能抛出异常的代码 ... f.close() # 可能无法执行
-
路径分隔符:
# 错误示例:硬编码路径分隔符 bad_path = "folder" + "\\" + "file.txt" # Windows特定 # 正确做法:使用os.path.join
-
编码问题:
# 错误示例:未指定编码导致乱码 f = open("data.txt", "r") # 使用系统默认编码 # 正确做法:明确指定encoding参数
通过掌握这些内容,可以高效处理从简单文本读写到复杂二进制数据操作的各种场景。实际应用中需根据需求选择合适的模式和方法,并特别注意资源管理和异常处理。