Python3 文件操作:从基础到高级的完整指南
文件操作是编程中常见的任务,Python 提供了简洁而强大的文件处理能力。无论是读取配置文件、处理数据还是日志记录,掌握文件操作都是必备技能。本文将全面介绍 Python3 中的文件操作,包括读写文本文件、二进制文件、上下文管理器以及常见的文件处理场景。
文件操作基础
打开文件:open() 函数
使用内置的 open() 函数打开文件,返回一个文件对象。基本语法:
1
| file = open(file_path, mode='r', encoding=None)
|
file_path:文件路径(相对路径或绝对路径)
mode:打开模式(常用模式如下)
encoding:编码方式(如 'utf-8',文本文件推荐指定)
常用打开模式:
| 模式 |
描述 |
'r' |
只读模式(默认),文件不存在则报错 |
'w' |
写入模式,文件存在则清空内容,不存在则创建 |
'a' |
追加模式,在文件末尾添加内容,不存在则创建 |
'r+' |
读写模式 |
'b' |
二进制模式(如 'rb' 读取二进制文件,'wb' 写入二进制文件) |
关闭文件:close() 方法
文件操作完成后必须关闭,释放系统资源:
1 2 3
| file = open('example.txt', 'r')
file.close()
|
注意:如果忘记关闭文件,可能导致资源泄露,尤其是在处理大量文件时。
文本文件读写
读取文本文件
常用读取方法:
read(size):读取指定字节数,默认读取全部内容
readline():读取一行内容
readlines():读取所有行,返回列表
- 直接迭代文件对象(高效读取大文件)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| with open('example.txt', 'r', encoding='utf-8') as f: content = f.read() print(content)
with open('example.txt', 'r', encoding='utf-8') as f: for line in f: print(line.strip())
with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(f"共 {len(lines)} 行")
|
写入文本文件
常用写入方法:
write(string):写入字符串
writelines(iterable):写入字符串序列(如列表)
1 2 3 4 5 6 7 8 9 10 11 12 13
| with open('output.txt', 'w', encoding='utf-8') as f: f.write("第一行内容\n") f.write("第二行内容\n")
with open('output.txt', 'a', encoding='utf-8') as f: f.write("第三行内容\n")
lines = ["Python\n", "文件操作\n", "示例\n"] with open('lines.txt', 'w', encoding='utf-8') as f: f.writelines(lines)
|
上下文管理器:with 语句
使用 with 语句处理文件是推荐的方式,它会自动关闭文件,即使发生异常也能保证资源释放:
1 2 3 4 5 6 7
| with open('example.txt', 'r') as f: content = f.read()
print(f.closed)
|
相比传统的 open() + close() 方式,with 语句更安全、简洁,是处理文件的最佳实践。
二进制文件操作
处理图片、音频、视频等二进制文件时,需要使用二进制模式(添加 'b' 到模式中),且不需要指定编码:
1 2 3 4 5 6 7 8
| with open('image.jpg', 'rb') as f: data = f.read() print(f"图片大小:{len(data)} 字节")
with open('source.jpg', 'rb') as src, open('copy.jpg', 'wb') as dst: dst.write(src.read())
|
文件和目录管理
结合 os 和 pathlib 模块,可以进行文件和目录的管理操作:
os 模块常用操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import os
os.makedirs('data/logs', exist_ok=True)
os.rename('old.txt', 'new.txt')
if os.path.exists('temp.txt'): os.remove('temp.txt')
os.rmdir('empty_dir')
for root, dirs, files in os.walk('data'): print(f"目录:{root}") for file in files: print(f" 文件:{os.path.join(root, file)}")
|
pathlib 模块(Python3.4+,面向对象风格)
pathlib 提供了更直观的面向对象接口,推荐用于路径处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| from pathlib import Path
file_path = Path('data/report.txt')
if file_path.exists(): print(f"{file_path} 存在")
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text("使用 pathlib 写入的内容", encoding='utf-8')
content = file_path.read_text(encoding='utf-8') print(content)
new_path = file_path.parent / 'log.txt' print(new_path)
|
常见文件操作场景
读取大文件(内存高效)
处理大文件时,避免一次性读取全部内容,应逐行处理:
1 2 3 4 5 6 7 8
| with open('large_file.txt', 'r', encoding='utf-8') as f: line_number = 1 for line in f: if 'error' in line.lower(): print(f"第 {line_number} 行包含错误信息:{line.strip()}") line_number += 1
|
CSV 文件处理
对于 CSV 格式的数据,可以使用内置的 csv 模块:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import csv
with open('data.csv', 'r', encoding='utf-8', newline='') as f: reader = csv.reader(f) header = next(reader) print(f"表头:{header}") for row in reader: print(f"数据行:{row}")
data = [ ['姓名', '年龄', '城市'], ['张三', '25', '北京'], ['李四', '30', '上海'] ] with open('output.csv', 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(data)
|
临时文件处理
使用 tempfile 模块创建临时文件 / 目录,适合临时存储数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import tempfile
with tempfile.NamedTemporaryFile(mode='w+', encoding='utf-8', delete=False) as f: f.write("这是临时文件内容") f.seek(0) print(f.read())
with tempfile.TemporaryDirectory() as temp_dir: print(f"临时目录:{temp_dir}") temp_file = Path(temp_dir) / 'temp.txt' temp_file.write_text("临时目录中的文件")
|
文件编码与异常处理
处理编码问题
读取文本文件时,应明确指定编码(通常是 utf-8),避免编码错误:
1 2 3 4 5 6 7 8
| try: with open('text.txt', 'r', encoding='utf-8') as f: content = f.read() except UnicodeDecodeError: print("文件编码不是 utf-8,尝试其他编码...") with open('text.txt', 'r', encoding='gbk') as f: content = f.read()
|
完整的异常处理示例
文件操作可能出现多种异常(如文件不存在、权限不足等),应妥善处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from pathlib import Path
file_path = Path('data.txt')
try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() print(f"成功读取 {file_path},内容长度:{len(content)}") except FileNotFoundError: print(f"错误:文件 {file_path} 不存在") except PermissionError: print(f"错误:没有权限访问 {file_path}") except UnicodeDecodeError: print(f"错误:文件 {file_path} 编码错误") except Exception as e: print(f"处理文件时发生未知错误:{e}")
|
总结
Python 文件操作核心要点:
- 优先使用
with 语句(上下文管理器)处理文件,自动管理资源
- 文本文件使用
'r'/'w'/'a' 模式,指定编码(如 utf-8)
- 二进制文件使用
'rb'/'wb' 模式,不指定编码
- 处理大文件时,采用逐行读取方式,避免占用过多内存
- 使用
os 或 pathlib 模块进行文件和目录管理
- 始终添加异常处理,应对文件不存在、编码错误等问题