如何使用 Python 代码修改 JSON 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?
修改 json 文件并创建新文件夹拷贝至指定路径
问题:
求助于 python 代码来协助完成以下任务:
代码:
import os import json import shutil def 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 result def 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_result def 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_str def 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 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?的详细内容,更多请关注其它相关文章!