求助:编写Python脚本批量提取JSON文件中Email字段及解决解码错误
问题解决与批量提取脚本实现
先修正单个文件的错误
你的脚本存在两个问题导致报错:
- 错误使用
json.loads():这个函数用于解析JSON格式的字符串,而你传入的是文件名"file.json",应该用json.load()读取文件对象。 - 语法错误:
print (json_data["Email"]缺少闭合的右括号)。
修正后的单个文件提取脚本:
import json # 打开文件并加载JSON数据 with open("file.json", "r", encoding="utf-8") as f: json_data = json.load(f) # 提取Email字段 print(json_data["Email"])
批量提取所有JSON文件的Email值
要处理数百个JSON文件,可以用glob模块匹配目录下所有.json文件,遍历处理,同时添加异常处理避免单个文件出错导致脚本中断:
import json import glob # 匹配当前目录下所有.json文件(可修改路径,比如"./json_files/*.json") json_files = glob.glob("*.json") for file_path in json_files: try: with open(file_path, "r", encoding="utf-8") as f: json_data = json.load(f) # 提取Email,若不存在则标记为缺失 email = json_data.get("Email", "Email字段缺失") print(f"文件 {file_path} 的Email: {email}") # 可选:将结果写入输出文件 with open("emails_result.txt", "a", encoding="utf-8") as out_f: out_f.write(f"{file_path}: {email}\n") except json.JSONDecodeError: print(f"文件 {file_path} 不是有效的JSON格式") except Exception as e: print(f"处理文件 {file_path} 时出错: {str(e)}")
关键说明
glob.glob("*.json"):匹配当前目录下所有后缀为.json的文件,若JSON文件在子目录,可修改路径为"./子目录名/*.json"。json_data.get("Email", "Email字段缺失"):用get方法避免因文件中无Email字段导致KeyError。- 异常处理:捕获JSON解码错误和其他异常,确保脚本能继续处理剩余文件。
内容的提问来源于stack exchange,提问作者motocrosser41
相关产品推荐
相关产品推荐

