【问题标题】:How to loop over several .json files [duplicate]如何循环多个.json文件[重复]
【发布时间】:2020-09-11 08:51:56
【问题描述】:

我在同一个目录中有几个具有相同结构的 .json 文件。我想从每个 json 文件的某些键中创建一个唯一的 csv 文件。

遍历一个文件一切正常。这里是脚本的快照:

import json, os
import csv

input_file = open ('JSON/test.json')
json_array = json.load(input_file)
object_list = []

for obj in json_array:

    for item in obj['objects']:
        object_details = {"_system_object_id":None,"preview_url":None,"original_download_url":None,"original_url":None}
        object_details['_system_object_id'] = item['_system_object_id']
        try:
            object_details['preview_url'] = item['do']['do_digitalobject'][0]['versions']['preview']['url']
        except:
            print("not found")
        try:
            object_details['original_download_url'] = item['do']['do_digitalobject'][0]['versions']['original']['download_url']
        except:
            print("not found")
        try:
            object_details['original_url'] = item['do']['do_digitalobject'][0]['versions']['original']['url']
        except:
            print("not found")

        #object_details['type'] = item['type']
        object_list.append(object_details)

    print(object_list)

如何处理文件夹中的所有.json文件?

谢谢

【问题讨论】:

    标签: python io listdir


    【解决方案1】:

    使用listdir,您可以在指定目录中找到所有.json 文件,然后遍历它们并应用您的逻辑:

    from os import listdir
    from os.path import isfile, join
    import json
    
    dir_path = "full/path/to/dir"
    object_list = []
    # get all json full paths of the json files in dir_path
    all_json_files = [join(dir_path, f) for f in listdir(dir_path) if isfile(join(dir_path, f)) and f.endswith(".json")]
    
    # iterate over the paths and apply your logic
    for file_path in all_json_files:
        with open(file_path) as input_file:
            json_array = json.load(input_file)
            for obj in json_array:
                # your business logic
                object_list.append(object_details)
    print(object_list)
    

    【讨论】:

      猜你喜欢
      • 2012-10-11
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多