从多个目录读取多个json文件

问题描述

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

我玩耍,想到了这样的东西:

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()

非常感谢您的帮助

解决方法

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()  
,

您可以使用os.walk并将顶级目录指定为directory_name。

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()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...