如何使用 Python 代码修改 JSON 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?
本篇文章向大家介绍《如何使用 Python 代码修改 JSON 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

修改 json 文件并创建新文件夹拷贝至指定路径
问题:
求助于 python 代码来协助完成以下任务:
- 修改文件夹内 json 文件的指定字段。
- 将修改后的 json 文件和文件夹内其他文件(如 jpg 和 avi)拷贝到一个新的路径下。
- 如果新路径不存在,需要创建新文件夹。
代码:
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 文件的指定字段,并将其与文件夹内的其他文件复制到新的路径?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注米云公众号!
