【发布时间】:2020-02-24 03:02:36
【问题描述】:
基本上有一个名为 subfolders 的 JSON 对象列表,它需要保存来自 2 个文件的信息 - 1 个来自名为 json_files 的列表,另一个存储在名为 table_files 的列表中。
来自json_files 和table_files 的信息需要按顺序分别包含在每个 JSON 对象中。
到目前为止,我能够输出我的 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))
【问题讨论】:
-
如何获得
json_files和table_files -
编辑了我原来的帖子。基本上通过子目录并将它们附加到基于后缀的列表中
标签: python json list file object