我尝试以这种方式生成输出文件,首先将7个实体转换为第一个json文件,然后将接下来的7个实体转换为第二个json文件,依此类推,直到最后。
data_path = 'C:/Users/User/Desktop/Tables/'
for i, data_item in enumerate(data):
with open(data_path + str(i) + '.json', 'w') as outfile:
outfile.write(simplejson.dumps({'entities': [data]}, indent=4, ignore_nan=True))我上面的脚本为1个Json文件生成1个实体,但我真的需要为每个输出Json文件生成7个实体。
发布于 2019-09-17 04:13:24
因为一次只能迭代一个实体,所以每个JSON文件只能获得一个实体
for i, data_item in enumerate(data):此外,根据问题中的代码,我假设您正在迭代目录中的文件(虽然按照编写,您将只迭代字符串中的字符,但我离题了)。
要获得您要查找的每个JSON的7个实体,您需要在每次迭代中创建该列表,或者以7为一组迭代该列表(我推荐使用chunks方法here)。
data_path = 'C:/Users/User/Desktop/Tables/'
# Assume data is a list of filenames in a directory
# In this case, data_item will be a list of *up to* 7 entities
for i, data_item in enumerate(chunks(data, 7)):
with open(f'{data_path}{i}.json', 'w') as outfile:
outfile.write(simplejson.dumps({'entities': data_item}, indent=4, ignore_nan=True))https://stackoverflow.com/questions/57962978
复制相似问题