25、Python 文件操作与JSON处理:从基础到实战
Python 文件操作与JSON处理:从基础到实战
文章概览
本文全面解析Python文件操作与JSON数据处理的核心技术,涵盖with
语句上下文管理、open
函数模式对比、文本/二进制文件操作、配置文件解析实战、json
模块高级用法及中文处理技巧。通过丰富的代码示例和实际案例,帮助开发者掌握文件与JSON的高效处理方法,并提供三个针对性练习题巩固知识。
一、Python文件操作精要
1.1 文件操作基础
# 传统文件操作方式
file = None
try:
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
print(content)
finally:
if file:
file.close()
# 现代推荐方式(使用with语句)
with open('example.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
关键要点:
with
语句自动处理资源释放,避免文件泄漏- 显式指定编码格式(推荐utf-8)
- 使用
read()
读取全部内容,readline()
逐行读取,readlines()
获取列表
1.2 文件模式深度对比
模式 | 描述 | 文件存在 | 文件不存在 |
---|---|---|---|
r | 只读 | 正常打开 | 抛出异常 |
w | 写入 | 清空内容 | 创建新文件 |
a | 追加 | 末尾写入 | 创建新文件 |
rb | 二进制读 | 同r模式 | 同r模式异常 |
w+ | 读写模式 | 清空内容 | 创建新文件 |
注意事项:
- 二进制模式用于非文本文件(如图片、视频)
w
模式具有破坏性,重要文件操作前建议备份- 网络传输建议使用二进制模式
1.3 配置文件解析实战
# config.ini
[database]
host = localhost
port = 3306
username = admin
# 解析代码
config = {}
with open('config.ini', 'r') as f:
current_section = None
for line in f:
line = line.strip()
if line.startswith('[') and line.endswith(']'):
current_section = line[1:-1]
config[current_section] = {}
elif '=' in line and current_section:
key, value = line.split('=', 1)
config[current_section][key.strip()] = value.strip()
print(config['database']['port']) # 输出: 3306
扩展技巧:
- 使用
configparser
标准库处理标准INI格式 - 复杂配置建议使用YAML或TOML格式
- 敏感信息应通过环境变量传递
二、JSON处理进阶
2.1 核心方法解析
import json
data = {
"name": "张三",
"age": 30,
"courses": ["Python", "Data Science"]
}
# 序列化操作
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str) # 正确显示中文
# 反序列化操作
restored_data = json.loads(json_str)
print(restored_data['name']) # 输出: 张三
# 文件操作
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
2.2 中文处理与高级参数
关键参数说明:
ensure_ascii=False
:禁用ASCII转码,保留中文indent=4
:美化输出,增强可读性sort_keys=True
:按键名排序输出default=str
:处理不可序列化对象
中文编码陷阱示例:
# 错误示范(默认ensure_ascii=True)
print(json.dumps({"测试": "数据"}))
# 输出: {"\u6d4b\u8bd5": "\u6570\u636e"}
# 正确解决方案
print(json.dumps({"测试": "数据"}, ensure_ascii=False))
# 输出: {"测试": "数据"}
三、实战练习题
3.1 日志分析器
# 统计error出现次数
def analyze_errors(log_file):
error_count = 0
with open(log_file, 'r', encoding='utf-8') as f:
for line in f:
if '[ERROR]' in line.upper():
error_count += 1
return error_count
3.2 数据持久化存储
def save_records(records, filename):
with open(filename, 'w', encoding='utf-8') as f:
json.dump({
"timestamp": datetime.now().isoformat(),
"data": records
}, f, ensure_ascii=False, indent=2)
3.3 异常处理优化
def safe_file_operation(filename):
try:
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"文件 {filename} 不存在")
except json.JSONDecodeError:
print("JSON格式错误")
except Exception as e:
print(f"未知错误: {str(e)}")
最佳实践总结
- 始终使用
with
语句进行文件操作 - JSON处理显式指定
ensure_ascii=False
- 重要操作添加异常处理机制
- 大文件处理建议使用流式读取
- 敏感数据避免明文存储
通过掌握这些核心技术与实践经验,开发者可以高效安全地处理各类文件操作和JSON数据交互需求。