I'm opening a lot of files at the beginning of my program and I'd like to avoid using 50+ separate lines of 'with open(....) as ....'. I'm looking for a way to map the file names to the variable names that the data will be stored in so that I can use a 'for' loop to open all files and save a lot of lines of code.
It seemed intuitive to me that a dictionary would suit this purpose well, but if I use the variable names as values, I get a 'name 'variableName' is not defined' error. I also tried storing the variable names as strings and while this doesn't produce an error message, it also doesn't seem to actually store the data (ie when I try to call the variable afterwards, it says the variable is not defined).
fileMapDict = {'file1': var1, 'file2': var2, 'file3': var3}
for file in fileMapDict:
with open(file, 'r') as data:
fileMapDict[file] = json.load(data)
As I say, this code produces a variable not defined error when I run the code, can anyone suggest a way to make this work?
答案 0 :(得分:3)
You don't need to have a separate variable if you have the data in the dictionary.
files = ['file1', 'file2', 'file3'] # list of file names to open
fileMapDict = {} # empty dictionary to store the data in
for file in files:
with open(file, 'r') as data:
fileMapDict[file] = json.load(data) # write data to dictionary with the file name as the key