import json
# 打开并读取 JSON 文件
def read_json_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
except FileNotFoundError:
print(f"文件 {file_path} 未找到。")
return None
except json.JSONDecodeError:
print(f"文件 {file_path} 不是有效的 JSON 格式。")
return None
# 示例用法
file_path = 'example.json'
json_data = read_json_file(file_path)
if json_data is not None:
print(json_data)
import json 导入 Python 的内置 json 模块,用于处理 JSON 数据。read_json_file 的函数,接收一个参数 file_path,表示要打开的 JSON 文件的路径。with open(file_path, 'r', encoding='utf-8') as file 打开文件,确保文件在读取后自动关闭。json.load(file) 将文件内容解析为 Python 对象(通常是字典或列表)。FileNotFoundError) 和 JSON 解码错误 (json.JSONDecodeError),并返回 None。read_json_file 函数,并检查返回的数据是否为 None,如果不是,则打印数据。如果你需要进一步的帮助或有其他问题,请告诉我!
上一篇:python的random用法
下一篇:python argsort
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站