在Python 2.7中通过循环目录加载多个.json文件(Loading more than one .json file in Python 2.7 by looping through a di

编程入门 行业动态 更新时间:2024-10-27 17:12:08
在Python 2.7中通过循环目录加载多个.json文件(Loading more than one .json file in Python 2.7 by looping through a directory)

我在一个目录中有三个.json文件,我试图通过这个目录来加载所有三个.json文件。 然而,一些有趣的事情发生了:代码不会产生错误,但它只加载三个.json文件中的一个。 我可以看到它是这样做的,因为我将json.load函数分配给一个变量,然后在解释器中输入变量['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)

I have three .json files in a directory, and I'm trying to loop through this directory to load all three .json files. However something interesting happens: the code does not produce an error, but it only loads one of the three .json files. I can see that it does this because I am assigning the json.load function to a variable, and then entering variable['someKey']['someInnerKey'] in the interpreter (the .json files have one level of nesting).

Below is the code I am using. I've spent some time searching through many posts here dealing with reading and opening .json files, but I haven't found the one "Aha!" post as of yet. I'll keep digging, but if anyone has any suggestions or tips, they would be much appreciated.

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)

最满意答案

尝试:

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

Try:

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)

Then your variables dictionary will contain the loaded json with the filename as the key rather than just overwriting variable

更多推荐

本文发布于:2023-07-22 10:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   加载   文件   目录   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!