在日常开发中,文件读写是最常见的基础操作之一。无论是处理配置文件、日志,还是数据导入导出,都离不开它。
参考文章:Python 文件读写 | 简单一点学习 easyeasy.me
1. 基础文件操作
Python 提供了一个内置函数 open()
用来打开文件,返回一个文件对象。
python
# 打开文件
f = open("example.txt", "r") # 以只读模式打开
# 读取内容
content = f.read()
print(content)
# 关闭文件
f.close()
基本步骤就是:打开 → 操作 → 关闭 。
不过,推荐用 with
语句,这样会自动关闭文件,更安全:
python
with open("example.txt", "r") as f:
content = f.read()
print(content)
# 这里文件已经自动关闭
2. 文件操作模式
open()
的第二个参数决定了文件的打开模式,常用模式如下:
模式 | 含义 |
---|---|
'r' |
只读(文件必须存在) |
'w' |
写入(会清空原文件,没有则创建) |
'a' |
追加(写在文件末尾,没有则创建) |
'rb' |
以二进制模式读取 |
'wb' |
以二进制模式写入 |
'ab' |
以二进制模式追加 |
'r+' |
读写(文件必须存在) |
'w+' |
写读(会清空原文件) |
'a+' |
追加读写 |
示例:
python
# 写入文件
with open("example.txt", "w") as f:
f.write("Hello Python\n")
# 追加文件
with open("example.txt", "a") as f:
f.write("Another line\n")
3. 读取文件内容的多种方式
Python 提供了多种读取方式,可以根据文件大小和需求选择:
python
# 1. 读取全部
with open("example.txt", "r") as f:
data = f.read()
print(data)
# 2. 按行读取到列表
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
# 3. 一行一行读取(适合大文件)
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
# 4. 指定字节数读取
with open("example.txt", "r") as f:
chunk = f.read(5) # 读取前5个字符
print(chunk)
4. 字符编码问题
默认情况下,open()
使用系统默认编码(Windows 上是 gbk
,Linux/Mac 是 utf-8
)。
为了避免乱码,建议显式指定编码:
python
# 推荐做法
with open("example.txt", "r", encoding="utf-8") as f:
print(f.read())
常见编码:
utf-8
(推荐)gbk
(Windows 常见)ascii
(纯英文文件)
如果读取时编码错误,可以这样处理:
python
with open("example.txt", "r", encoding="utf-8", errors="ignore") as f:
print(f.read())
5. 二进制文件操作
处理图片、音频、视频等非文本文件时,需要用二进制模式。
python
# 读取图片
with open("image.png", "rb") as f:
data = f.read()
print(len(data))
# 写入二进制文件
with open("copy.png", "wb") as f:
f.write(data)
6. 处理大文件
如果文件很大,直接 read()
会占用大量内存,这时建议分块读取。
python
# 按固定大小读取
with open("bigfile.txt", "r", encoding="utf-8") as f:
while True:
chunk = f.read(1024) # 每次读 1KB
if not chunk:
break
print(chunk, end="")
或者用生成器:
python
def read_in_chunks(file, size=1024):
while True:
data = file.read(size)
if not data:
break
yield data
with open("bigfile.txt", "r", encoding="utf-8") as f:
for part in read_in_chunks(f):
print(part)
7. 文件路径与跨平台兼容性
直接写路径容易出错,建议用 os
和 pathlib
来拼接路径。
python
import os
# 自动拼接路径(跨平台)
file_path = os.path.join("data", "example.txt")
# 确保文件夹存在
os.makedirs("data", exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
f.write("Hello World")
使用 pathlib
更优雅:
python
from pathlib import Path
p = Path("data") / "example.txt"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Hello Pathlib", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
8. 异常处理
读写文件时可能出现各种错误,比如文件不存在 、权限不足 、编码错误 等。
建议用 try-except
捕获异常。
python
try:
with open("nofile.txt", "r", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("文件不存在")
except PermissionError:
print("没有权限")
except Exception as e:
print("发生错误:", e)
9. 最佳实践
- 总是使用
with
语句,确保文件能正常关闭。 - 显式指定编码,尤其是跨平台环境下。
- 处理大文件时分块读取,避免一次性占用太多内存。
- 路径操作用
os.path
或pathlib
,避免硬编码分隔符。 - 捕获异常,让程序更稳健。
- 写文件时确认数据安全,必要时先写到临时文件再替换。