Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将存储在一个文件夹中的多个json文件读入Python中的不同词典?_Python_Json_Dictionary - Fatal编程技术网

如何将存储在一个文件夹中的多个json文件读入Python中的不同词典?

如何将存储在一个文件夹中的多个json文件读入Python中的不同词典?,python,json,dictionary,Python,Json,Dictionary,假设文件夹中有20个JSON文件,我想在python程序中读取并存储到20个不同的字典中。您可以使用列表保存文件名,然后对每个文件名应用dict读取 import json from pathlib import Path files = ['a.txt', 'b.txt', 'c.txt'] # ... dicts = [json.loads(Path(file).read_text()) for file in files] 你真的是指一系列字典,是吗?还是一本词典?您的密钥是基于文件

假设文件夹中有20个JSON文件,我想在python程序中读取并存储到20个不同的字典中。

您可以使用
列表保存文件名,然后对每个文件名应用dict读取

import json
from pathlib import Path

files = ['a.txt', 'b.txt', 'c.txt']  # ...
dicts = [json.loads(Path(file).read_text()) for file in files]

你真的是指一系列字典,是吗?还是一本词典?您的密钥是基于文件名的吗?可以使用字典列表或嵌套字典。没有键不是基于文件名的。所有.json文件/dict都有相同的键,但值不同。我相信读取可以简化为
json.load(Path(file))
@RufusVS nope
dicts=[json.load(open(file)),用于文件中的文件]
工作但不关闭文件,Path().readtext-doesach文件在加载函数返回时立即关闭。@RufusVS自动关闭仅当您使用contexthandler
并将open(filename)作为f:…
-如果您只使用
f=open(filename))您还需要执行
f.close()`这不是
f=open(filename
。这是
somefunc(open(filename))
。当
somefunc
返回时,文件引用将被关闭。