【问题标题】:Python read JSON files from all sub-directoriesPython 从所有子目录中读取 JSON 文件
【发布时间】:2019-11-13 22:36:03
【问题描述】:

我有以下文件夹结构:

Directory    
    - Subdirectory 1:
       file.json
    - Subdirectory 2:
       file.json
    - Subdirectory 3:
       file.json
    - Subdirectory 4:
       file.json

如何使用 Pandas 读取这些 JSON 文件?

【问题讨论】:

  • 使用glob模块获取所有json文件然后迭代?

标签: json python-3.x pandas


【解决方案1】:

试试这个代码:

import pandas as pd
from pathlib import Path

files = Path("Directory").glob("**/*.json")

for file in files:
    df = pd.read_json(file)

要了解有关将 JSON 字符串转换为 Pandas 对象的更多信息:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    import glob, os
    working_directory = os.getcwd()
    
    sub_directories = [active_directory + "/" + x for x in os.listdir(working_directory) if os.path.isdir(active_directory + "/"+x)]
    all_json_files = []
    
    for sub_dir in sub_directories:
        os.chdir(sub_dir)
        for file in glob.glob("*.json"):
            all_json_files.append(sub_dir + "/" + file)
    
    #Get back to original working directory
    os.chdir(working_directory)
    
    list_of_dfs = [pd.read_json(x) for x in all_json_files]
    

    从那里开始,如果所有 json 文件具有相同的结构,您可以将它们连接起来以获得一个数据帧:

    final_df = pd.concat(list_of_dfs)
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      相关资源
      最近更新 更多