问题描述
我有多个目录,都包含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()
@H_404_7@非常感谢您的帮助
解决方法
将
os.walk
与str.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()