在目录中找到 JSON 个文件并打开它们

Find JSON files in a directory and open them

我的目标是在目录中搜索特定的 JSON 文件并读取它们,以便我可以将它们的内容导出为 Excel 文件。

目录列表:\Linkedin\linkedin_hb_ma21-260eb95ebb-d87d-XX1-XXX-XXX1cX

详情: (linkedin hb_ma): 文件夹包含几个文件夹 (year-day) // (year-day): 包含几个文件夹 with (member ID) // (member ID): 包含一个 Json 个文件

我的代码:

import os
import json
from pprint import pprint
import win32com.client as win32 # pip install pywin32

rootDir = 'C:/Users/Adam/Desktop/Linkedin/linkedin_hb_ma'
for dirName, subdirList, fileList in os.walk(rootDir , topdown=False):
    if dirName.endswith("1eb95ebb-d87d-4aac-XX-XX182"):
        abs_path = os.path.join(dirName, file)
        print('Found directory: %s' % dirName)
        #print(fileList)
        for file in fileList:
            if file.endswith("activities.json"):
                #print('\t%s' % file)
                json_data = json.loads(open(abs_path).read())
                pprint(json_data)

错误:FileNotFoundError:[Errno 2] 没有这样的文件或目录:'activities.json' 注意:我的 python 文件在另一个工作目录中。

有人有想法吗? 非常感谢

问题是 os.walk 不会 return fileList 的绝对文件路径,您需要像这样连接父目录和文件名:

abs_path = os.path.join(dirName, file)
json_data = json.loads(open(abs_path).read())