【问题标题】:Loading more than one .json file in Python 2.7 by looping through a directory通过遍历目录在 Python 2.7 中加载多个 .json 文件
【发布时间】:2017-05-04 07:57:55
【问题描述】:

我在一个目录中有三个 .json 文件,我正在尝试遍历该目录以加载所有三个 .json 文件。然而,有趣的事情发生了:代码不会产生错误,但它只加载三个 .json 文件之一。我可以看到它这样做是因为我将 json.load 函数分配给一个变量,然后在解释器中输入 variable['someKey']['someInnerKey'] (.json 文件具有一层嵌套)。

下面是我正在使用的代码。我花了一些时间在这里搜索了许多关于阅读和打开 .json 文件的帖子,但我还没有找到“啊哈!”发布至今。我会继续挖掘,但如果有人有任何建议或提示,他们将不胜感激。

import json, os  
for filename in os.listdir('D:/path1/path2/'):
    if filename.endswith('.json'):
        with open(os.path.join('D:/path1/path2/',filename)) as json_file:
            variable = json.load(json_file)

【问题讨论】:

  • 您在每次迭代时都分配给variable,因此会覆盖之前的计算
  • 好的 - 这是有道理的。谢谢!

标签: python json python-2.7


【解决方案1】:

试试:

import json, os  

variables = {}

for filename in os.listdir('D:/path1/path2/'):
    if filename.endswith('.json'):
        with open(os.path.join('D:/path1/path2/',filename)) as json_file:
            variables[filename] = json.load(json_file)

然后您的variables 字典将包含以文件名作为键的加载的json,而不是仅仅覆盖variable

【讨论】:

  • 嘿 Drew G. - 这很有效。我可以看到带有 variables.keys() 的 .json 文件,并且可以访问每个文件中的 sub 和 sub-sub 键。谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多