Python将多个文件夹中的JSON集合导出到单独的制表符分隔文件中

时间:2017-06-10 21:46:32

标签: python json

我有500个文件夹,每个文件夹包含不同数量(范围在20-40之间)的JSON集合。我可以通过以下给出herehere

的答案,在Python中手动和单独提取每个文件夹的内容
import os, json
path_to_json = 'C:/Users/SomeFolder'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
#list all the files in the folder
print (json_files)

for js in json_files:
    with open(os.path.join(path_to_json, js)) as json_file:
#can only print to screen all the json files - need help saving to a tab-delimited file 
       print (json.load(json_file))

然而,考虑到这必须做500次,这将是非常费力的并且显然非常烦人。一种更快速的自动化方法,可以将每个JSON文件夹的内容重复提取到制表符分隔文件中,这是非常受欢迎的。感谢

1 个答案:

答案 0 :(得分:1)

import os, json


current_directory = os.path.dirname(os.path.realpath(__file__))

all_directories = [x[0] for x in os.walk(current_directory)]

for directory in all_directories:
    path_to_json = directory
    json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
    #list all the files in the folder
    print (json_files)

    for js in json_files:
        with open(os.path.join(path_to_json, js)) as json_file:
    #can only print to screen all the json files - need help saving to a tab-delimited file 
           print (json.load(json_file))

这将找到执行此脚本的所有文件夹。然后它将迭代文件夹并完成工作。您需要将其复制到存储文件夹的位置。