如何使用 Python 代码修改 JSON 文件中的字段并复制文件夹中的文件到新路径?
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《如何使用 Python 代码修改 JSON 文件中的字段并复制文件夹中的文件到新路径?》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
修改 json 和复制文件夹中的文件到新路径
以下 python 代码可用于修改 json 文件中的部分字段,并复制文件夹中的 json 文件、jpg 文件和 avi 文件到新路径。
import os import json import shutil # 获取 json 文件的路径 def get_json_data(old_json_path): json_file_paths = [] 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) json_file_paths.append(old_json_file_path) return json_file_paths # 获取文件夹的路径 def get_dir_name(dir_name): dir_names = [] for root, dirs, files in os.walk(dir_name): for dir in dirs: dirpath = os.path.join(root, dir) dir_names.append(dirpath) return dir_names # 读取 json 文件并更新字段 def read_json(filepath): with open(filepath, 'r', encoding='utf-8') as f: json_data = f.read() if json_data: json_data_dict = eval(json_data) json_data_dict.update({"filename": filepath.split('\\')[-2].replace('.dav', '.avi')}) return json_data_dict # 写入 json 文件 def write_json(filepath, newdata): with open(filepath, 'w', encoding='utf-8') as r: json.dump(newdata, r, indent=4, ensure_ascii=false) # 复制 json 文件和其他文件到新路径 def copy_files(old_path, new_path): dir_names = get_dir_name(old_path) for dir in dir_names: 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_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) other_files = [] for root, dirs, files in os.walk(old_path): for file_name in files: if file_name.endswith('.jpg') or file_name.endswith('.avi'): other_files.append(os.path.join(old_path, file_name)) for file in other_files: shutil.copy(file, new_path) # 主函数 if __name__ == "__main__": old_path = r'd:\ss' new_path = r'd:\json' copy_files(old_path, new_path)
eof 错误解决
eof 错误是因为尝试在文件末尾执行 eval(json_data),而此时 json_data 为空。可以通过检查 json_data 是否为空来避免此错误。
import os import json file_path = r'F:\vscode_pj\pj_test\test_data\1\2.json' with open(file_path) as f: data = f.read() if data: b = eval(data)
以上就是《如何使用 Python 代码修改 JSON 文件中的字段并复制文件夹中的文件到新路径?》的详细内容,更多关于的资料请关注公众号!