import json
import os
for i in os.listdir(r'C:\Users\86198\Desktop\KL1打完标签'):
with open(i, 'r', encoding='utf-8') as fp:
json_data = json.load(fp)
data = json_data['shapes'] # 作用是截取json文件中我们需要的键值
import pandas as pd
df1 = pd.DataFrame(data) # 作用是将josn数据转化成图表可读类型
df1.to_json('json处理后数据.json', orient='records') # 作用是创建新数据的json文件
with open("json处理后数据.json", encoding="utf-8") as f:
full_data = json.load(f) # 取出json所有数据放入字典中
f.close()
full_data1 = [] # 创建新列表方便存储josn数据
for i in full_data: # 遍历旧json文件中的数据
i.pop('shape_type') # 删除shape_type的键值
i.pop('flags') # 删除flags的键值
full_data1.append(i) # 注入新列表
with open('json处理后数据.json', 'w+', encoding="utf-8") as f: # w+读写 从开头开始编辑,即原有内容会被删除
json.dump(full_data1, f, indent=2, ensure_ascii=False) # 此处已经形成新的json文件
f.close()
Traceback (most recent call last):
File "C:\Users\86198\AppData\Roaming\JetBrains\PyCharm2022.1\scratches\文件处理.py", line 4, in
with open(i, 'r', encoding='utf-8') as fp:
FileNotFoundError: [Errno 2] No such file or directory: '.idea'
在您的代码中,您使用了os.listdir()函数来获取文件夹中的文件名,然后把文件名作为文件路径的一部分,使用open()函数打开文件。
但是,os.listdir()函数返回的是文件名,并不包含文件路径。例如,如果文件夹C:\Users\86198\Desktop\KL1打完标签中有一个文件名为file1.json,那么os.listdir()函数会返回一个列表['file1.json'],而不会包含文件路径。
因此,您需要使用os.path.join()函数来拼接文件路径,然后才能用open()函数打开文件。例如:
import json
import os
folder = r'C:\Users\86198\Desktop\KL1打完标签'
for file in os.listdir(folder):
file_path = os.path.join(folder, file) # 拼接文件路径
with open(file_path, 'r', encoding='utf-8') as fp:
json_data = json.load(fp)
这样,您就可以成功地读取文件夹中的每一个文件了。
另外,您也可以使用os.makedirs()函数来创建文件夹,例如:
import json
import os
folder = r'C:\Users\86198\Desktop\KL1打完标签'
output_folder = os.path.join(folder, 'output') # 定义输出文件夹路径
if not os.path.exists(output_folder):
os.makedirs(output_folder) # 创建文件夹
for file in os.listdir(folder):
file_path = os.path.join(folder, file) # 拼接文件路径
with open(file_path, 'r', encoding='utf-8') as fp:
json_data = json.load(fp)
data = json_data['shapes']
import pandas as pd
df1 = pd.DataFrame(data)
output_file = os.path.join(output_folder, file) # 拼接输出文件路径
with open(output_file, 'w+', encoding='utf-8') as fp:
json.dump(df1, fp, indent=2, ensure_ascii=False)
这样,您就能够将文件处理完成后的数据保存到新的文件夹中了。
总结一下,您需要在原有的代码基础上添加以下内容: