首页 新闻 会员 周边

本人为python初学者,求一段python代码,能够批量修改路径下指定文件中json的指定内容,如{filename:1.dav}修改为{filename:1.avi}

0
悬赏园豆:200 [已解决问题] 解决于 2021-10-20 09:09

修改前的json内容为:
{
"filename":"1.dav";
}

需要修改为:
{
"filename":"2.avi";
}

目前已经大致知道可以使用
import json
path = u'D:'
dict = {}
get_json_date = json.load(f)
修改json内容
with open(path,'w',endcode='utf8') as r:
json_dump = json.dump()
r.close()

不清楚如何批量获取及修改json内的filename,视频名称对应文件夹名称,请大佬指教,谢谢!

问题补充:

目前写出的代码如下,在自己家写的代码报了 PermissionError: [Errno 13] Permission denied 错误

import json
import os
def get_json_data(old_json_path):
for root,dirs,files in os.walk(old_json_path):
for file_name in files:
if file_name.endswith('.json'):
with open(old_json_path,'r',encoding='utf8') as f:
content = f.read()
json_content = eval(content)
print(type(json_content))
if 'fileName' in json_content:
content_str = json_content.replace('1.dav','1.avi')
json_data = json.loads(content_str)
print(type(json_data))
with open(old_json_path,'w',encoding='utf8') as r:
r.write(old_json_path)

if name == "main":
old_json_path = r"D:\python\练习\改json内容\test"
get_json_data(old_json_path)

奔三的人的主页 奔三的人 | 初学一级 | 园豆:6
提问于:2021-10-17 20:07
< >
分享
最佳答案
1
# -*- coding: utf-8 -*-
import json


def main():
    json_str = '{"filename": "1.dav"}'
    path = "result.json"

    get_json_data = json.loads(json_str)
    with open(path, "w") as r:
        get_json_data["filename"] = "2.avi"  # 这一步就是修改json的内容
        r.write(json.dumps(get_json_data))


if __name__ == "__main__":
    main()

Hi,有几点注意下:

  1. 如果用python3,默认就是utf8, 写入文件的时候不用特意指定 encode
  2. 使用 with 的话,出了with的作用域范围会自动关闭文件,不用调用 r.close
  3. 使用 json.loads 和 json.dumps,不是 json.load 和 json.dump (这2个函数需要额外的参数)
收获园豆:200
wang_yb | 老鸟四级 |园豆:4891 | 2021-10-19 11:04

感谢感谢

奔三的人 | 园豆:6 (初学一级) | 2021-10-19 11:07

您好:
就是目前我还想将json更改的内容
get_json_data["filename"] = "2.avi" # 后面的“2.avi”更改为获取到文件夹名称后,使用文件夹的名称直接更改,文件夹的名称导出时就已经被命名为xxx.avi的格式了,
获取时使用遍历文件夹的方式获取到文件夹名称:
list_name = []
for root,dirs,files in os.walk(file_path):
for file_name in files:
if file_name.endswith(".dav"):
list_name.append
我想的是将文件夹名称添加到列表中,然后将列表中的名称和相对应的文件夹名称匹配后,批量修改文件夹中的json文件,json文件中的内容均为{“fileName”:“1.dav”},添加到列表后的代码应该如何写,您能再指点下吗

奔三的人 | 园豆:6 (初学一级) | 2021-10-19 11:44

@奔三的人: 你好,能否把你的代码贴出来,我直接再上面改

wang_yb | 园豆:4891 (老鸟四级) | 2021-10-29 12:00

@wang_yb: 您好,目前代码已经完成了,请您看下代码是否可以精简一些,目前这个脚本完成了一个获取旧文件夹内的内容并修改后,拷贝至新的文件夹的功能

-- coding:utf-8 --

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:
print(dir)
json_file_list = get_json_data(dir)
for json_file in json_file_list:
print(json_file)
dir_name = dir.split("\")[-1]
new_dir_name = os.path.join(new_json_path,dir_name)
if os.path.exists(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)
else:
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)

奔三的人 | 园豆:6 (初学一级) | 2021-10-29 14:13

@奔三的人: 已经完成了,great! 😃
有几个小建议:

  1. dir是python标准库的函数,最好不要用来做为变量名称
  2. if name == "main": 这个应该是 if name == "main":
  3. 代码用3个反引号圈起来,格式会保持。比如你的代码我要看到话,要调整缩进,很麻烦。比如:
# ```python
# your codes
# ``` 
  1. 最后一段代码中的 if/else 有点冗余(里面的内容重复了),其实就是判断文件夹不存在时,创建个文件夹。我改成下面这样:
            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)
wang_yb | 园豆:4891 (老鸟四级) | 2021-10-29 15:15

@wang_yb: 多谢您的指点!谢谢!

奔三的人 | 园豆:6 (初学一级) | 2021-10-29 15:17
其他回答(1)
0

1.把json转成集合列表
2.循环列表属性,修改

筱浬 | 园豆:601 (小虾三级) | 2021-10-18 15:47

可以麻烦您再细说一下吗

支持(0) 反对(0) 奔三的人 | 园豆:6 (初学一级) | 2021-10-18 21:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册