如何使用 Python 代码修改 JSON 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?

如何使用 python 代码修改 json 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?

修改 json 文件并创建新文件夹拷贝至指定路径

问题:

求助于 python 代码来协助完成以下任务:

修改文件夹内 json 文件的指定字段。将修改后的 json 文件和文件夹内其他文件(如 jpg 和 avi)拷贝到一个新的路径下。如果新路径不存在,需要创建新文件夹。

代码:

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

import osimport jsonimport shutildef get_json_data(old_json_path):    result = []    for root, dirs, files in os.walk(old_json_path):        for file_name in files:            if file_name.endswith('.json'):                old_json_file_path = os.path.join(root, file_name)                result.append(old_json_file_path)    return resultdef get_dir_name(dir_name):    dir_name_result = []    for root, dirs, files in os.walk(dir_name):        for dir in dirs:            dirpath = os.path.join(root, dir)            dir_name_result.append(dirpath)    return dir_name_resultdef read_json(filepath):    with open(filepath, 'r', encoding='utf-8') as f:        json_data = f.read()        json_data_str = eval(json_data)        json_data_str.update({"fileName": filepath.split("\")[-2].replace(".dav", ".avi")})    return json_data_strdef write_json(filepath, newdata):    with open(filepath, 'w', encoding='utf-8') as r:        json.dump(newdata, r, indent=4, ensure_ascii=False)def copy_other_files(old_json_path, new_json_path):    for root, dirs, files in os.walk(old_json_path):        for file_name in files:            if not file_name.endswith('.json'):                old_json_filepath = os.path.join(root, file_name)                new_dir_name = os.path.join(new_json_path, root.split("\")[-1])                if not os.path.exists(new_dir_name):                    os.mkdir(new_dir_name)                shutil.copy(old_json_filepath, new_dir_name)if __name__ == "__main__":    old_json_path = r'D:ss'    new_json_path = r'D:json'    dirlist = get_dir_name(old_json_path)    for dir in dirlist:        json_file_list = get_json_data(dir)        for json_file in json_file_list:            dir_name = dir.split("\")[-1].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)            shutil.copy(json_file, new_dir_name)            newdata = read_json(new_dir_name + "\" + os.path.basename(json_file))            write_json(new_dir_name + "\" + os.path.basename(json_file), newdata)        copy_other_files(dir, new_json_path)

登录后复制

解决问题:

问题一:

确保 get_json_data 函数正确过滤不需要复制的文件。在此示例中,仅拷贝 json 文件。

问题二:

在读取空字符串时,eval 会引发错误。将 bool(data) 检查添加到 eval 之前,以避免空字符串错误。

以上就是如何使用 Python 代码修改 JSON 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?的详细内容,更多请关注【创想鸟】其它相关文章!

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

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2183518.html

(0)
上一篇 2025年2月25日 15:45:56
下一篇 2025年2月19日 20:17:53

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论