读取目录中的所有json文件 - python

我在要读取并附加到列表的目录中包含多个(400)json文件,其中包含字典。我试过像这样遍历目录中的所有文件:

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)

我不断收到以下错误:

FileNotFoundError: [Errno 2] No such file or directory

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

for file in os.listdir(path_to_jsonfiles):
    print(file)

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

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

循环中出现问题了吗?

python参考方案

您的代码有两个错误:

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)

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

将字符串分配给numpy.zeros数组[重复] - python

This question already has answers here: Weird behaviour initializing a numpy array of string data                                                                    (4个答案)         …