import xmltodict
import json
import os
# xml to json
def xmlToJson(xml_str):
try:
json_dict = xmltodict.parse(xml_str, encoding='utf-8')
json_str = json.dumps(json_dict, indent=2)
return json_str
except:
pass
# json to xml
def jsonToXml(json_str):
try:
json_dict = json.loads(json_str)
xml_str = xmltodict.unparse(json_dict, encoding='utf-8')
except:
xml_str = xmltodict.umparse({'request': json_dict}, encoding='utf-8')
finally:
return xml_str
# load xml file
def load_json(xml_path):
# 获取xml文件
xml_file = open(xml_path, 'r')
xml_str = xml_file.read()
# 将读取的xml字符串转换为字典
json_dict = xmltodict.parse(xml_str)
# 将字典转换为json格式的字符串
json_str = json.dumps(json_dict, indent=2)
return json_str
path = "D:\\Filerec\\NEU-DET\\IMAGES"
filelist = os.listdir(path) #该文件夹下所有的文件(包括文件夹)
count=0
for file in filelist:
print(file)
for file in filelist: #遍历所有文件
Olddir=os.path.join(path,file) #原来的文件路径
if os.path.isdir(Olddir): #如果是文件夹则跳过
continue
filename=os.path.splitext(file)[0] #文件名
filetype=os.path.splitext(file)[1] #文件扩展名
print(path+"\\"+file)
json_1 = load_json(path+"\\"+file)
newtype=json
newpath="D:\\Coding\\python\\annotations"
Newdir = (newpath+'res'+str(count)+'.json')
print(Newdir)
with open(Newdir, 'w', encoding='utf-8') as f:
f.write(json_1)
#Newdir=os.path.join(path,str(count).zfill(6)+fileatype) #用字符串函数zfill 以0补全所需位数
#os.rename(Olddir,Newdir)#重命名
count+=1