本质上有一个JSON对象列表,subfolders
它需要保存2个文件中的信息-1个来自列表中的信息json_files
,另一个存储在名为中的列表中table_files
。
来自每个JSON对象中的信息,json_files
并且table_files
需要按顺序分别包含一次。
到目前为止,我能够分别输出我的JSON对象列表和将在这些对象中保存的信息,但是不能以我需要的格式一起执行,这就是问题所在。
我的输出subfolders
列表的代码:
subfolders = [ f.path for f in os.scandir(rootdir) if f.is_dir() ]
subfolders = [sub.replace(rootdir + '\\', '') for sub in subfolders]
obj = { conf_name:{} for conf_name in subfolders }
with open('summary.json', 'w') as f:
json.dump(obj, f, indent=2)
我的用于输出json_data
和table_data
信息的代码将存储在子文件夹中:
json_data = []
for i in json_files:
with open(i) as f:
json_data.append(json.load(f))
table_data = []
for i in table_files:
with open(i) as f:
table_data.append([line.rstrip('\n') for line in f])
combined = []
for j, t in zip(json_data, table_data):
combined.append(j)
combined.extend(t)
with open('summary.json', 'w') as f:
json.dump(combined, f, indent=2)
所需的输出:
{
"subfolder1": {
"json_data": "{content from first json_data file in list}"
"table_data": "content from first table_data file in list"
},
"subfolder2": {
"json_data": "{content from second json_data file in list}"
"table_data": "content from second json_data file in list"
}
}
因此,我想知道如何将所有内容组合在一起以产生所需的格式。非常感谢您的任何帮助,谢谢。
编辑:用于获取列表json_files
和table_files
:
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".json"):
json_files.append(os.path.join(subdir, file))
if file.endswith(".list"):
table_files.append(os.path.join(subdir, file))
您可以尝试以下方法:
summary = {}
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".json"):
json_files.append(os.path.join(subdir, file))
if file.endswith(".list"):
table_files.append(os.path.join(subdir, file))
json_data = []
for i in json_files:
with open(i) as f:
json_data.append(json.load(f))
table_data = []
for i in table_files:
with open(i) as f:
table_data.append([line.rstrip('\n') for line in f])
summary[subdir] = {
'json_data': json_data,
'table_data': table_data
}
with open('summary.json', 'w') as f:
json.dump(summary, f, indent=2)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句