如何使用 Python 代码修改 JSON 文件中的字段并拷贝相关文件?

如何使用 python 代码修改 json 文件中的字段并拷贝相关文件?

需求梳理

根据你的描述,你需要一段 python 代码来满足以下需求:

修改 json 文件中的部分字段将修改后的 json 文件和文件夹中的其他类型文件(如 .jpg、.avi)拷贝到新的路径在新路径下创建必要的文件夹

python 代码

import osimport jsonimport shutildef modify_json_copy_files(old_json_path, new_json_path):    # 获取所有 json 文件    json_files = []    for root, dirs, files in os.walk(old_json_path):        for file_name in files:            if file_name.endswith('.json'):                json_files.append(os.path.join(root, file_name))    # 遍历每个 json 文件    for json_file in json_files:        # 读入 json 数据并修改字段        with open(json_file, 'r', encoding='utf-8') as f:            json_data = f.read()            if bool(json_data):                json_data_str = eval(json_data)                if isinstance(json_data_str, dict):                    json_data_str.update({"filename": json_file.split("")[-2].replace(".dav", ".avi")})        json_data_str = json_data        # 写入修改后的 json 数据        new_json_file = os.path.join(new_json_path, os.path.basename(json_file))        with open(new_json_file, 'w', encoding='utf-8') as f:            json.dump(json_data_str, f, indent=4, ensure_ascii=false)        # 拷贝其他类型文件        dir_name = json_file.split("")[-2].replace(".dav", ".avi")        new_dir_name = os.path.join(new_json_path, dir_name)        if not os.path.exists(new_dir_name):            os.mkdir(new_dir_name)        for file_name in os.listdir(json_file.rsplit('', 1)[0]):            if file_name != os.path.basename(json_file) and (file_name.endswith('.jpg') or file_name.endswith('.avi')):                old_file_path = os.path.join(json_file.rsplit('', 1)[0], file_name)                new_file_path = os.path.join(new_dir_name, file_name)                shutil.copy(old_file_path, new_file_path)# 设置旧 json 路径和新 json 路径old_json_path = 'c:pathtooldjson'new_json_path = 'c:pathtonewmodifiedjson'modify_json_copy_files(old_json_path, new_json_path)

eof 报错处理

立即学习“Python免费学习笔记(深入)”;

当 f.read() 的结果为空时,eval(json_data) 会引发 syntaxerror: unexpected eof while parsing 错误。为了避免这种情况,可以在 eval 之前检查 json_data 是否为空,如下:

if bool(json_data):    json_data_str = eval(json_data)    if isinstance(json_data_str, dict):        json_data_str.update({"fileName": json_file.split("")[-2].replace(".dav", ".avi")})json_data_str = json_data

以上就是如何使用 Python 代码修改 JSON 文件中的字段并拷贝相关文件?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1352173.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 16:36:03
下一篇 2025年12月12日 16:10:38

相关推荐

发表回复

登录后才能评论
关注微信