Python文件读写方法详解
1. 打开文件
使用Python内置的open()函数打开文件,该函数返回文件对象:
基本语法:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
常用参数:
file: 文件路径(字符串或字节对象)
mode: 访问模式(默认为'r')
encoding: 编码格式(如'utf-8')
errors: 编码错误处理方式
1.1. 文件访问模式
| 模式 | 描述 |
|------|------|
| 'r' | 只读(默认) |
| 'w' | 只写(会覆盖已有文件) |
| 'a' | 追加(文件不存在则创建) |
| 'x' | 排他性创建(文件存在则报错) |
| 'b' | 二进制模式(可与其他模式组合) |
| '+' | 读写模式(可与其他模式组合) |
1.2. 打开文件示例
# 以只读方式打开文本文件
file = open('example.txt', 'r', encoding='utf-8')
# 以二进制写入方式打开
file = open('data.bin', 'wb')
# 以追加读写方式打开
file = open('log.txt', 'a+', encoding='utf-8')
2. 读取文件内容
2.1. 读取整个文件
使用read()方法读取整个文件内容:
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
2.2. 逐行读取
使用readline()读取单行
使用readlines()读取所有行到列表
直接遍历文件对象
# 使用readline()
with open('example.txt', 'r') as file:
first_line = file.readline()
print(first_line)
# 使用readlines()
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line, end='')
# 直接遍历文件对象(推荐方式)
with open('example.txt', 'r') as file:
for line in file:
print(line, end='')
2.3. 读取指定字节
with open('data.bin', 'rb') as file:
# 读取前10个字节
chunk = file.read(10)
print(chunk)
3. 写入文件
3.1. 写入字符串
使用write()方法写入字符串:
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, World!\n")
file.write("Python文件操作教程\n")
3.2. 写入多行
使用writelines()方法写入字符串列表:
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open('multi_line.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
3.3. 二进制写入
data = b'\x00\x01\x02\x03\x04\x05'
with open('binary_data.bin', 'wb') as file:
file.write(data)
4. 文件指针操作
4.1. 获取当前指针位置
with open('example.txt', 'r') as file:
file.read(5)
position = file.tell()
print(f"当前指针位置: {position}")
4.2. 移动文件指针
使用seek()方法移动指针:
语法:seek(offset, whence=0)
offset: 偏移量(字节数)
whence: 参考位置
0: 文件开头(默认)
1: 当前位置
2: 文件末尾
with open('example.txt', 'r+b') as file:
# 移动到文件开头后第5字节
file.seek(5)
# 移动到文件末尾前10字节
file.seek(-10, 2)
# 获取文件大小
file.seek(0, 2) # 移动到文件末尾
size = file.tell()
print(f"文件大小: {size} 字节")
5. 上下文管理器(with语句)
使用with语句自动管理文件资源,无需手动关闭文件:
# 自动关闭文件
with open('example.txt', 'r') as file:
content = file.read()
# 文件会在这里自动关闭
# 等价于不使用with的代码
file = open('example.txt', 'r')
try:
content = file.read()
finally:
file.close()
6. 文件和目录操作
6.1. 检查文件是否存在
import os
if os.path.exists('example.txt'):
print("文件存在")
else:
print("文件不存在")
6.2. 创建目录
# 创建单级目录
os.makedirs('data', exist_ok=True)
# 创建多级目录
os.makedirs('data/subdir', exist_ok=True)
6.3. 删除文件和目录
# 删除文件
os.remove('example.txt')
# 删除目录(必须为空)
os.rmdir('data')
# 删除目录及其内容(谨慎使用!)
import shutil
shutil.rmtree('data')
6.4. 重命名文件
os.rename('old_name.txt', 'new_name.txt')
7. 常见问题处理
7.1. 处理文件编码问题
# 使用errors参数处理编码错误
with open('example.txt', 'r', encoding='utf-8', errors='ignore') as file:
content = file.read()
# 或使用errors='replace'替换非法字符
with open('example.txt', 'r', encoding='utf-8', errors='replace') as file:
content = file.read()
7.2. 处理大文件
使用逐块读取处理大文件:
CHUNK_SIZE = 4096 # 4KB
with open('large_file.bin', 'rb') as file:
while True:
chunk = file.read(CHUNK_SIZE)
if not chunk:
break
# 处理数据块
process_data(chunk)
7.3. 处理文件操作异常
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("文件不存在!")
except PermissionError:
print("没有文件访问权限!")
except IOError as e:
print(f"发生I/O错误: {e}")
8. 总结
本教程详细介绍了Python文件读写的基本方法:
使用open()函数打开文件,支持多种访问模式
通过read()、readline()、readlines()等方法读取文件内容
使用write()和writelines()方法写入文件
利用seek()和tell()操作文件指针位置
强烈推荐使用with语句自动管理文件资源
通过os和shutil模块进行文件系统操作
注意处理文件编码、大文件处理和异常情况
掌握这些技术将帮助您高效地处理各种文件操作任务,为数据持久化和处理奠定坚实基础。







