Suppose there are 20 JSON files in a folder and I want to read & store them into 20 different dictionaries in a python program.
You may use a list
to hold the filenames, then apply the dict reading for each
import json
from pathlib import Path
files = ['a.txt', 'b.txt', 'c.txt'] # ...
dicts = [json.loads(Path(file).read_text()) for file in files]
I believe the read could be simplified as
json.load(Path(file))
@RufusVS nope.
dicts = [json.load(open(file)) for file in files]
works but doesn't close files, Path().readtext doesEach file is closed as soon as the load function returns.
@RufusVS autoclosing is only happening if you use the contexthandler
with open(filename) as f: ....
- if you just usef = open(filename)) you need to do
f.close()` as wellThis is not
f=open(filename
. This issomefunc(open(filename))
. whensomefunc
returns, the file reference will be closed.