
需求梳理
根据你的描述,你需要一段 python 代码来满足以下需求:
python 代码
import os
import json
import shutil
def 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:\path\to\old\json'
new_json_path = 'c:\path\to\new\modified\json'
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 文件中的字段并拷贝相关文件?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号