【问题标题】:read mutiple json files from multiple directories从多个目录读取多个 json 文件
【发布时间】:2020-12-02 04:21:15
【问题描述】:

我有多个目录,它们都包含 JSON 文件。 我知道如何在 ONE 目录中读取所有内容,但不知道如何在不指定目录名称的情况下在所有目录中读取它们。

我玩了一圈,想出了这样的东西:

import json
import os

path_to_json = 'path/to/dir/with/dirs' 
json_files = [pos_json for pos_json in os.listdir(path_to_json)]


for json_file in json_files:
    filename = str(json_file + "/") # here something like "*.json"
    with open(filename, 'r') as myfile:
        data=myfile.read()

非常感谢任何帮助

【问题讨论】:

    标签: python json directory


    【解决方案1】:

    您可以使用os.walk 并将顶级目录作为目录名称。

    import os
    
    root = "<path-to-dir>"
    
    for path, subdirs, files in os.walk(root):
        for filename in files:
            if filename.endswith('.json'):
                with open(filename, 'r') as myfile:
                    data = myfile.read()
    

    【讨论】:

      【解决方案2】:

      os.walkstr.endswith 一起使用

      例如:

      path_to_json = 'path/to/dir/with/dirs' 
      json_files = []
      
      for root, dirs, files in os.walk(path_to_json):
          for f in files:
              if f.endswith('.json'):      #Check for .json exten
                  json_files.append(os.path.join(root, f))    #append full path to file
                  
      for json_file in json_files:
          with open(json_file, 'r') as myfile:
              data=myfile.read()  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-19
        • 2014-07-23
        • 2013-09-04
        • 1970-01-01
        • 2016-08-18
        • 2015-04-25
        • 1970-01-01
        相关资源
        最近更新 更多