使用Python实现文件读写自动化
Python通过内置的open()
函数和文件操作模块实现高效的文件自动化处理。以下是关键操作及示例代码:
一、基础文件操作
- 读取文件
# 读取整个文件
with open('data.txt', 'r', encoding='utf-8') as f:content = f.read() # 全部内容存入字符串lines = f.readlines() # 按行存入列表# 逐行读取(内存友好)
with open('log.csv', 'r') as file:for line in file:print(line.strip()) # 移除换行符
- 写入文件
# 覆盖写入
with open('report.txt', 'w') as f:f.write("每日报告\n")f.writelines(["数据1: 完成\n", "数据2: 进行中\n"])# 追加写入
with open('log.txt', 'a') as f:f.write(f"{datetime.now()}: 操作记录\n")
二、自动化场景实现
- 批量重命名文件
import os
for filename in os.listdir('docs'):if filename.endswith('.jpg'):new_name = f"image_{filename.split('.')[0]}.png"os.rename(f'docs/{filename}', f'docs/{new_name}')
- 数据清洗与转换
with open('raw_data.csv', 'r') as input_file, \open('clean_data.csv', 'w') as output_file:for line in input_file:cleaned = line.replace(';', ',').upper()output_file.write(cleaned)
- 定时备份文件
import shutil, datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M")
shutil.copy2('database.db', f'backups/db_backup_{timestamp}.db')
三、高级应用
- 处理Excel文件(需安装
openpyxl
)
from openpyxl import load_workbook
wb = load_workbook('财务表.xlsx')
sheet = wb.active
for row in sheet.iter_rows(min_row=2, values_only=True):if row[3] > 10000: # 筛选金额>10000的行print(f"大额交易: {row[0]} {row[2]}")
- PDF文本提取(需安装
PyPDF2
)
import PyPDF2
with open('合同.pdf', 'rb') as pdf_file:reader = PyPDF2.PdfReader(pdf_file)page = reader.pages[0]print(page.extract_text()[:100]) # 提取首页前100字符
四、最佳实践
- 路径处理
使用pathlib
模块避免路径兼容性问题:
from pathlib import Path
config_path = Path('config') / 'settings.ini' # 自动处理不同OS路径分隔符
- 异常处理
try:with open('重要文件.txt', 'r') as f:data = f.read()
except FileNotFoundError:print("错误: 文件不存在")
except PermissionError:print("错误: 无读取权限")
- 大文件处理
使用缓冲读取避免内存溢出:
chunk_size = 1024 * 1024 # 1MB
with open('large_video.mp4', 'rb') as src:while chunk := src.read(chunk_size):# 处理数据块process(chunk)
注意事项:
- 所有路径建议使用原始字符串(如
r"C:\文件夹"
)或正斜杠- 文本文件务必指定编码(推荐
utf-8
)- 操作重要文件前先备份
- 使用
with
语句确保文件自动关闭