我在一个目录中有三个.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
更多推荐
发布评论