【发布时间】:2019-12-19 00:18:36
【问题描述】:
我在下面提到的文件夹结构中的不同文件夹中有同名的 json 文件
folder1/
file1.json
file2.json
file3.json
folder2/
file1.json
file2.json
file3.json
file4.json
folder3/
file1.json
file2.json
file3.json
file4.json
file5.json
....
结合所有文件夹中可用的 json 文件以创建单个 json 文件的最佳方法是什么。 file1.json 中的键在它存在的所有文件夹中都是唯一的
到目前为止,我可以想到以下方法,但感觉很慢,因为每个 json 文件大约 5 MB。
from pathlib import Path
output_dir = Path(location_of_output_folder)
output_dir.mkdir(parents=True, exist_ok=True)
# find all the folders
root_dir = Path(root_location_for_folders)
folders = [fld for fld in root_dir.iterdir() if fld.is_dir()]
# find all the unique file names
all_filenames = []
for fld in folders:
for f in fld.glob('*.json'):
all_filenames.append(f.name)
## Approach 1
# Join file that possibly exists across all the folders by creating empty list
for f in list(set(all_filenames)):
f_data = []
for fld in folders:
if (fld / f).is_file():
with open(fld /f, 'r') as fp:
f_data.append(json.load(fp))
with open(output_dir / f, 'w') as fp:
json.dump(f_data, fp, indent=4)
## Approach 2
# Join file that possibly exists across all the folders by creating empty dict
for f in list(set(all_filenames)):
f_data = {}
for fld in folders:
if (fld / f).is_file():
with open(fld /f, 'r') as fp:
f_data.update(json.load(fp))
with open(output_dir / f, 'w') as fp:
json.dump(f_data, fp, indent=4)
有没有更好(更快)的方法。我只担心时间,对pythonic解决方案不感兴趣
谢谢
更新#1:应该合并具有相同文件名的文件。对不起,如果我不清楚。每个文件将有几个键 (l1, l2, l3, l4) 与所有文件相似
例子
一个。 folder1中file1.json的结构
{
k1: {
l1: 11,
l2: 12,
l3: 13,
l4: 14,
},
k2: {
l1: 21,
l2: 22,
l3: 23,
l4: 24,
}
.....
}
一个。 folder2中file2.json的结构
{
k8: {
l1: 41,
l2: 42,
l3: 43,
l4: 44,
},
k9: {
l1: 51,
l2: 52,
l3: 53,
l4: 54,
}
.....
}
【问题讨论】:
-
我认为没有什么比加载所有文件然后转储结果更好的了。试图通过直接合并文件来做到这一点是行不通的,因为它不尊重 JSON 语法。
-
你能分享一些示例 JSON 吗? 我只是担心时间,对 pythonic 解决方案不感兴趣 咦,这是为什么呢?
-
等一下,您要合并同名文件吗?您的帖子中不清楚。
-
@AMC 我更新了问题以包含更多信息
-
对不起,但仍不清楚:'folder1' 中的'file1.json' 有键 'k1,k2..' 和 'folder2' 中的 'file2.json' 有不同的键。好的,但是'folder2' 和其他文件夹中的 'file1.json' 是否与第一个 'file1.json' 具有相同的键?如果是这种情况,“合并”是什么意思,是否应该为每个相应的键连接所有值?