首页 新闻 赞助 找找看

求一段python代码,修改json及拷贝文件夹下的内容到新的路径下,新的路径没有文件夹,需要新建

0
悬赏园豆:20 [已解决问题] 解决于 2021-11-13 19:45

求一段代码,可以完成json内容部分字段的修改及拷贝文件夹内已经修改的json文件和其余类型的文件(如.jpg .avi)至新路径下的文件夹内,新建文件夹需要修改部分字段

文件夹如上所示

文件夹的里包含的内容有json文件,.jpg文件和.avi文件
目前的需求是将文件夹内的json文件修改部分字段后,连同照片和视频一起拷贝至一个新的路径,新的路径为空,需要创建一个新的文件夹,如下

上图为路径下本来的样子

上图为需要拷贝的样子

目前我已经写出修改json内容并将json内容拷贝到新路径下的代码:

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)

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)
   当我增加拷贝其它文件的代码时,会出现所有文件下的照片和avi文件拷贝到同一个文件夹下,这个问题困扰了我很久,不知道应该如何解决,请大佬指教,谢谢!
def other_file(old_json_path):
    avi_jpg = []
    for root,dirs,files in os.walk(old_json_path):
        for file_name in files:
            if file_name.endswith(".jpg") or file_name.endswith(".avi"):
                old_json_filepath = os.path.join(root,file_name)
                avi_jpg.append(old_json_filepath)
            else:
                print("文件不存在")
    return avi_jpg

另外请问一下,

json_date = f.read()
json_date_str = eval(json_date)

将文件夹读出来后再转化为字典会遇到一个EOF的报错,这是为什么导致的?

奔三的人的主页 奔三的人 | 初学一级 | 园豆:6
提问于:2021-11-08 21:40
< >
分享
最佳答案
1

问题一:“增加拷贝其它文件的代码时,会出现所有文件下的照片和avi文件拷贝到同一个文件夹下”
没复现出来,执行结果都是正常的(当前代码指挥拷贝 *.json 文件);
盲猜你 “拷贝其他文件” 没调试 json_file_list = get_json_data(dir) ,你不想复制的文件要在这个函数里过滤

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()
        if bool(json_data):
            json_data_str = eval(json_data)
            if isinstance(json_data_str, dict):
                json_data_str.update({"fileName":filepath.split("\\")[-2].replace(".dav",".avi")})
        else:
            json_data_str = json_data
    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)

if __name__ == "__main__":
    old_json_path = r'F:\vscode_pj\pj_test\test_data'
    new_json_path = r'F:\vscode_pj\pj_test\test_data2'
    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)

问题二:“遇到一个EOF的报错”
复现结果,当 f.read() 为空时 eval(json_date) 会报 “SyntaxError: unexpected EOF while parsing”

file_path = r'F:\vscode_pj\pj_test\test_data\1\2.json'

with open(file_path) as f:
    data = f.read()
    print(data)
    if bool(data):
        b = eval(data)
收获园豆:20
〆灬丶 | 老鸟四级 |园豆:2287 | 2021-11-09 10:00

您好,万分感谢您的回答,对于json会报EOF错误的问题是因为我的json中存在空文件导致,目前已知晓;对于第一个copy的问题,我重新写了一遍代码,仍然存在很多问题,能不能麻烦您再看一下下面的代码,拷贝json和拷贝其他文件的步骤已分开,但仍然无法复制并进行json的修改

import os
import json
import shutil
def get_json_date(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 otherfile_copy(old_json_path):
    otherfile = []
    for root,dirs,files in os.walk(old_json_path):
        for file in files:
            if file.endswith('.jpg') or file.endswith('.avi'):
                otherfile_path = os.path.join(root,file)
                otherfile.append(otherfile_path)
    return otherfile

def read_json(filepath):
    with open(filepath,'r',encoding='utf-8')as f:
        json_date = f.read()
        json_date_str = eval(json_date)
        json_date_str.update({"fileName":filepath.split("\\")[-2].replace(".dav",".avi")})
    return json_date_str

def write_json(filepath,newdate):
    with open(filepath,'w',encoding='utf-8')as r:
        json.dump(newdate,r,indent=4,ensure_ascii=False)

if __name__ == "__main__":
    old_json_path = r'D:\ss'
    new_json_path = r'D:\json'
    getjsondate = get_json_date(old_json_path)
    for jsonfile in getjsondate:
        new_dir_name = os.path.join(new_json_path,jsonfile.split("\\")[-2].replace(".dav",".avi"))
        otherfilecopy = otherfile_copy(old_json_path)
        for othercopy in otherfilecopy:
            if not os.path.exists(new_dir_name):
                os.mkdir(new_dir_name)
                shutil.copy(jsonfile,new_dir_name)
                shutil.copy(othercopy,new_dir_name)
                newdate = read_json(new_dir_name)
                write_json(new_dir_name,newdate)
            else:
                shutil.copy(jsonfile,new_dir_name)
                shutil.copy(othercopy,new_dir_name)
                newdate = read_json(new_dir_name)
                write_json(new_dir_name,newdate)
奔三的人 | 园豆:6 (初学一级) | 2021-11-09 22:11

@奔三的人:
我个人觉得你有2点事情,比完善这个代码的工能更重要

  1. 之前第一版的代码里,对应的函数是起什么作用的
  2. 两层 for 循环的 目的,分别是啥

(分别看看三版代码,你贴的第一版,我贴的一版,你贴的第二版;如果看不懂就断点调试,IDE自带的功能也好, python 的 pdb 功能也行)

# 你的第一版
    dirlist = get_dir_name(old_json_path)
    for dir in dirlist:

# 你的第二版
    getjsondate = get_json_date(old_json_path)
    for jsonfile in getjsondate:
〆灬丶 | 园豆:2287 (老鸟四级) | 2021-11-10 09:19

@韆: 您好:
谢谢您的问题指正,经过代码调试后,该问题已解决

奔三的人 | 园豆:6 (初学一级) | 2021-11-13 19:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册