【问题标题】:Reading all json files in a directory读取目录中的所有json文件
【发布时间】:2018-05-20 19:23:26
【问题描述】:

我有多个 (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 json directory


【解决方案1】:

您的代码有两个错误:

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)

【讨论】:

  • 是的,对不起,我看到我为附加位粘贴了错误的缩进。但是完整的文件路径就像一个魅力!你能解释一下"%s/%s" % 是做什么的吗?
  • @Lisadk 那就是所谓的字符串格式化。假设您想在字符串中放置一个变量。您可以使用%s 为字符串、%d 为整数等在字符串中分配占位符,而不是像full_filename = path_to_jsonfiles + "/" + file 那样做。在您声明像"%s/%s" 这样的字符串结构后,只需放入% 并在其中分配变量订购。
猜你喜欢
  • 2019-11-13
  • 1970-01-01
  • 2013-12-02
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多