免费python编程教程:https://pan.quark.cn/s/2c17aed36b72
在Python编程中,文件操作是连接程序与外部存储的桥梁。无论是读取配置文件、处理日志数据,还是存储程序运行结果,掌握文件操作技巧都能让开发效率大幅提升。本文将从基础读写讲起,逐步深入到高效处理、异常管理、二进制操作等高级场景,用实战案例帮助你快速掌握文件操作精髓。
Python通过open()
函数与文件建立连接,核心参数包括:
data/log.txt
)和绝对路径(如C:/project/data.csv
)模式 | 名称 | 行为 | 适用场景 |
---|---|---|---|
r | 只读 | 文件必须存在,否则报错 | 读取配置/日志 |
w | 覆盖写入 | 清空原文件,不存在则创建 | 生成新文件 |
a | 追加写入 | 文件末尾添加内容,不存在则创建 | 持续记录日志 |
r+ | 读写 | 文件必须存在,可读可写 | 修改文件中间内容 |
b | 二进制模式 | 与r/w/a组合使用 | 处理图片/音频等非文本 |
示例:读取UTF-8编码的文本文件
with open('notes.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content[:50]) # 打印前50个字符
手动关闭文件(file.close()
)存在两大风险:
推荐方案:使用with
语句自动管理
# 传统方式(易出错)
file = open('data.txt', 'w')
file.write('重要数据')
# 忘记close()导致数据未保存!
# 正确方式(自动关闭)
with open('data.txt', 'w') as file:
file.write('自动保存的数据')
# 离开with块后文件自动关闭
with open('config.json', 'r') as f:
full_content = f.read() # 返回整个字符串
print(full_content)
注意:大文件(如几百MB的日志)使用此方法会导致内存爆炸。
error_count = 0
with open('server.log', 'r') as f:
for line in f: # 逐行读取,内存占用恒定
if 'ERROR' in line:
error_count += 1
print(f"发现{error_count}个错误")
error_count = 0
with open('server.log', 'r') as f:
for line in f: # 逐行读取,内存占用恒定
if 'ERROR' in line:
error_count += 1
print(f"发现{error_count}个错误")
写入单行:
with open('output.txt', 'w') as f:
f.write('第一行内容\n') # 必须手动添加换行符
写入多行:
data = ['苹果\n', '香蕉\n', '橙子\n']
with open('fruits.txt', 'w') as f:
f.writelines(data) # 不会自动添加换行符!
避坑指南:若列表元素未包含换行符,需预先处理:
clean_data = [f"{item}\n" for item in ['苹果', '香蕉']]
tell()
:返回当前指针位置(字节偏移量)seek(offset, whence)
:移动指针 whence=0
(默认):从文件头计算whence=1
:从当前位置计算whence=2
:从文件尾计算示例:修改文件中间内容
with open('demo.txt', 'r+') as f:
# 定位到第5个字节
f.seek(5)
# 读取后续10个字符
print(f.read(10))
# 回到文件头插入内容
f.seek(0)
f.write('新开头')
处理图片、音频等非文本文件时,需使用二进制模式:
# 复制图片
with open('original.jpg', 'rb') as src:
data = src.read()
with open('copy.jpg', 'wb') as dst:
dst.write(data)
结构化二进制数据:使用 struct 模块解析
import struct
with open('data.bin', 'rb') as f:
# 读取4字节整数+8字节浮点数
int_data, float_data = struct.unpack('if', f.read(12))
统计错误和警告数量:
def analyze_log(log_path):
errors, warnings = 0, 0
with open(log_path, 'r') as f:
for line in f:
if 'ERROR' in line:
errors += 1
elif 'WARNING' in line:
warnings += 1
return errors, warnings
# 使用示例
err, warn = analyze_log('app.log')
print(f"错误:{err} 警告:{warn}")
处理缺失值并导出:
import csv
def clean_csv(input_path, output_path):
with open(input_path, 'r') as infile, \
open(output_path, 'w', newline='') as outfile:
reader = csv.DictReader(infile)
fieldnames = reader.fieldnames
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
for row in reader:
# 填充缺失的age字段为0
row['age'] = row.get('age', '0')
writer.writerow(row)
# 使用示例
clean_csv('raw_data.csv', 'cleaned_data.csv')
处理GB级日志文件:
def process_large_file(file_path, chunk_size=1024*1024): # 默认1MB
with open(file_path, 'r') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
# 处理每个数据块
analyze_chunk(chunk)
def analyze_chunk(chunk):
# 示例:统计块中的IP地址
ips = [line.split()[0] for line in chunk.splitlines()
if line.startswith('192.168')]
print(f"发现{len(ips)}个内网IP")
异常类型 | 触发场景 | 处理方案 |
---|---|---|
FileNotFoundError | 文件不存在 | 检查路径或创建文件 |
PermissionError | 无读写权限 | 检查文件权限或以管理员运行 |
IsADirectoryError | 试图将目录当作文件打开 | 确认路径指向文件而非目录 |
import os
def safe_write(file_path, content):
try:
# 确保目录存在
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w') as f:
f.write(content)
except IOError as e:
print(f"文件写入失败: {e}")
except Exception as e:
print(f"未知错误: {e}")
# 使用示例
safe_write('backup/2025.log', '系统备份数据')
pathlib
替代os.path
Python 3.4+推荐的路径操作方式:
from pathlib import Path
# 路径拼接
config_path = Path('config') / 'settings.ini'
# 检查文件是否存在
if config_path.exists():
print(config_path.read_text(encoding='utf-8'))
使用tempfile
模块安全创建临时文件:
import tempfile
# 创建临时文件(自动删除)
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as tmp:
tmp.write('临时数据')
tmp.seek(0)
print(tmp.read()) # 输出: 临时数据
# 离开with块后文件自动删除
处理超大文件时,使用mmap
减少I/O操作:
import mmap
with open('huge_file.dat', 'r+b') as f:
# 映射整个文件到内存
with mmap.mmap(f.fileno(), 0) as mm:
# 像操作字符串一样处理文件
print(mm[:100].decode('utf-8')) # 读取前100字节
with
语句:自动管理资源,避免泄漏encoding='utf-8'
r+
a
rb
/wb
FileNotFoundError
等特定异常pathlib
而非os.path
掌握这些技巧后,你可以轻松应对:
文件操作是Python编程的基础技能,更是连接数据与程序的桥梁。通过合理运用本文介绍的技巧,你将能编写出更高效、更健壮的代码。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。