Python open 读写文件实现脚本代码展示
MemoryDragon 上传于 2020-05-13 22:34
《Python open 读写文件实现脚本代码展示》
文件操作是编程中不可或缺的基础技能,Python通过内置的open()
函数提供了简洁高效的接口。本文将系统讲解Python中文件读写的基本方法、高级技巧及常见场景实现,结合代码示例与最佳实践,帮助读者快速掌握文件操作的核心能力。
一、文件操作基础
Python中文件操作的核心是open()
函数,其基本语法为:
file_object = open(file_path, mode='r', encoding=None)
参数说明:
-
file_path
:文件路径(相对或绝对路径) -
mode
:打开模式(默认为只读'r') -
encoding
:字符编码(如'utf-8')
1.1 常用打开模式
模式 | 描述 |
---|---|
r | 只读(默认) |
w | 写入(覆盖原有内容) |
x | 独占创建(文件已存在则报错) |
a | 追加写入 |
b | 二进制模式(如'rb') |
t | 文本模式(默认) |
+ | 读写模式(如'r+') |
1.2 文件关闭与上下文管理
手动关闭文件:
f = open('test.txt', 'r')
try:
content = f.read()
finally:
f.close() # 确保文件关闭
推荐使用with
语句自动管理资源:
with open('test.txt', 'r') as f:
content = f.read() # 无需显式调用close()
二、文件读取操作
2.1 完整读取文件
# 读取全部内容(大文件慎用)
with open('data.txt', 'r', encoding='utf-8') as f:
data = f.read()
print(data)
2.2 按行读取文件
方法1:readlines()
返回列表
with open('data.txt', 'r') as f:
lines = f.readlines() # 每行作为列表元素
for line in lines:
print(line.strip()) # 去除换行符
方法2:直接迭代文件对象(内存高效)
with open('data.txt', 'r') as f:
for line in f: # 逐行迭代
print(line.rstrip())
2.3 读取指定字节数
with open('large_file.bin', 'rb') as f:
chunk = f.read(1024) # 每次读取1024字节
while chunk:
process(chunk)
chunk = f.read(1024)
三、文件写入操作
3.1 写入字符串
# 覆盖写入
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('第一行内容\n')
f.write('第二行内容\n')
# 追加写入
with open('output.txt', 'a') as f:
f.write('追加的内容\n')
3.2 写入多行数据
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('multiline.txt', 'w') as f:
f.writelines(lines) # 注意不会自动添加换行符
3.3 二进制文件操作
# 写入二进制数据
image_data = b'\x89PNG\r\n\x1a\n...' # 示例二进制数据
with open('image.png', 'wb') as f:
f.write(image_data)
# 读取二进制数据
with open('image.png', 'rb') as f:
loaded_data = f.read()
四、高级文件操作技巧
4.1 同时读写文件(r+模式)
with open('modify.txt', 'r+') as f:
content = f.read()
f.seek(0) # 移动指针到开头
f.write('新内容' + content[5:]) # 修改前5个字符
4.2 文件指针操作
with open('position.txt', 'r+') as f:
print(f.tell()) # 当前指针位置
f.seek(10) # 移动到第10字节
data = f.read(5) # 读取5个字节
f.seek(0, 2) # 移动到文件末尾(2表示从末尾计算)
4.3 处理大文件
逐块处理示例:
def process_large_file(file_path, chunk_size=1024*1024):
with open(file_path, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
# 处理每个数据块
analyze_chunk(chunk)
五、实用脚本示例
5.1 日志文件分析器
def analyze_logs(log_file):
error_count = 0
with open(log_file, 'r') as f:
for line in f:
if 'ERROR' in line:
error_count += 1
print(f'发现 {error_count} 个错误日志')
analyze_logs('server.log')
5.2 CSV文件处理
import csv
# 写入CSV
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 25, 'New York'])
# 读取CSV
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
5.3 文件内容搜索工具
def search_in_files(directory, keyword):
import os
results = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
path = os.path.join(root, file)
try:
with open(path, 'r') as f:
if keyword in f.read():
results.append(path)
except UnicodeDecodeError:
continue
return results
print(search_in_files('./docs', 'Python'))
六、异常处理与最佳实践
6.1 常见异常处理
try:
with open('nonexistent.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print('文件不存在')
except PermissionError:
print('没有访问权限')
except UnicodeDecodeError:
print('文件编码错误')
else:
print('文件读取成功')
6.2 最佳实践总结
- 始终使用
with
语句管理文件 - 明确指定文件编码(推荐UTF-8)
- 处理大文件时使用流式读取
- 对关键操作添加异常处理
- 避免在循环中频繁打开/关闭文件
七、跨平台文件路径处理
使用os.path
模块处理路径:
import os
# 拼接路径
file_path = os.path.join('folder', 'subfolder', 'file.txt')
# 获取绝对路径
abs_path = os.path.abspath('relative_path.txt')
# 检查路径是否存在
if os.path.exists(file_path):
print('文件存在')
Python 3.4+推荐使用pathlib
模块:
from pathlib import Path
file = Path('docs') / 'report.txt'
if file.exists():
print(file.read_text(encoding='utf-8'))
八、性能优化技巧
8.1 缓冲写入
# 默认启用缓冲,如需禁用
with open('fast.txt', 'w', buffering=1) as f: # 行缓冲
f.write('即时写入每行')
8.2 批量写入
data_chunks = ['Chunk1\n', 'Chunk2\n', 'Chunk3\n']
with open('bulk.txt', 'w') as f:
f.writelines(data_chunks) # 比多次write()更高效
九、完整案例:文件备份工具
import shutil
import os
from datetime import datetime
def backup_files(source_dir, backup_dir):
# 创建带时间戳的备份目录
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
dest_dir = os.path.join(backup_dir, f'backup_{timestamp}')
os.makedirs(dest_dir, exist_ok=True)
# 遍历源目录并复制文件
for root, _, files in os.walk(source_dir):
for file in files:
src_path = os.path.join(root, file)
rel_path = os.path.relpath(src_path, source_dir)
dest_path = os.path.join(dest_dir, rel_path)
# 确保目标目录存在
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
# 复制文件
shutil.copy2(src_path, dest_path) # 保留元数据
print(f'备份完成至: {dest_dir}')
# 使用示例
backup_files('./project', './backups')
十、总结与扩展
Python的文件操作体系通过open()
函数和标准库模块提供了强大的文件处理能力。掌握基础读写模式后,可以进一步探索:
-
io
模块的高级I/O操作 -
tempfile
模块创建临时文件 -
pickle
模块序列化对象到文件 - 第三方库如
pandas
处理结构化数据
关键词:Python文件操作、open函数、文件读写模式、上下文管理器、二进制文件处理、大文件处理、路径处理、异常处理、文件备份
简介:本文全面介绍了Python中文件操作的核心方法,涵盖基础读写、高级技巧、实用脚本和最佳实践。通过代码示例演示了不同场景下的文件处理方案,包括文本/二进制文件操作、大文件处理、跨平台路径管理等,帮助开发者构建健壮的文件处理系统。