读取目录中的所有json文件

Lis*_*adk 3 python directory json

我有多个 (400) json 文件,其中包含一个目录中的 dict,我想读取这些文件并将其附加到列表中。我试过像这样循环遍历目录中的所有文件:

path_to_jsonfiles = 'TripAdvisorHotels'
alldicts = []
for file in os.listdir(path_to_jsonfiles):
    with open(file,'r') as fi:
        dict = json.load(fi)
alldicts.append(dict)
Run Code Online (Sandbox Code Playgroud)

我不断收到以下错误:

FileNotFoundError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)

但是,当我查看目录中的文件时,它为我提供了所有正确的文件。

for file in os.listdir(path_to_jsonfiles):
    print(file)
Run Code Online (Sandbox Code Playgroud)

只需使用文件名打开其中之一也可以。

with open('AWEO-q_GiWls5-O-PzbM.json','r') as fi:
    data = json.load(fi)
Run Code Online (Sandbox Code Playgroud)

在循环中是不是出错了?

Ali*_*maz 6

您的代码有两个错误:

1.file只是文件名。您必须编写完整的文件路径(包括其文件夹)。

2.你必须append在循环内使用。

总而言之,这应该有效:

alldicts = []
for file in os.listdir(path_to_jsonfiles):
    full_filename = "%s/%s" % (path_to_jsonfiles, file)
    with open(full_filename,'r') as fi:
        dict = json.load(fi)
        alldicts.append(dict)
Run Code Online (Sandbox Code Playgroud)