Python文件读写与JSON解析常用代码示例
使用内置的 open 函数配合 with 语句处理文件,利用 json 模块进行序列化与反序列化。

文件读写基础操作
通过指定模式(如 'r'、'w')打开文件,确保资源自动释放。

with 语句在块结束后自动关闭文件句柄,避免内存泄漏。读取时注意编码设置,写入时需确认路径权限。
JSON 数据解析流程
将 JSON 字符串转为 Python 字典,或把字典写回 JSON 文件。

import json
import os
def read_json_file(filepath):
if not os.path.exists(filepath):
return None
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
return data
except json.JSONDecodeError as e:
print(f"JSON 解析失败: {e}")
return None
def write_json_file(filepath, data):
try:
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
return True
except Exception as e:
print(f"写入失败: {e}")
return False
# 示例调用
data = {"name": "test", "value": 123}
write_json_file("output.json", data)
result = read_json_file("output.json")
print(result)
程序成功创建 output.json 并打印出包含 name 和 value 的字典。若文件损坏,控制台会输出解析错误信息。
使用 json.loads() 解析文本,json.dumps() 生成文本。处理嵌套结构时保持键名一致。
异常处理与数据验证
捕获 json.JSONDecodeError 防止程序崩溃。
当输入格式不符预期时,记录错误日志并返回默认值。检查文件是否存在可提前规避 FileNotFoundError。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













