'Assign variables to all files in a folder for access
I have a folder that contains'.pkl' files. I want to access the data inside those multiple files to plot my results.
I am getting an error when I try to do it with a for loop. All my .pkl files contain numbering in their filename like meta_room_1_reg.pkl, meta_room_2_reg.pkl and so on. So I want to assign a single variable to each and every one.
Currently, I am doing that with an if and find() statement. But that is not ideal.
My code is here:
all_files = glob.glob('D:/Master Thesis/MCDM Combined code/results/*.pkl')
for i, curr_file in enumerate(all_files):
with open(curr_file, 'rb') as f:
mydata = pickle.load(f)
if curr_file.find('1'):
myfile = mydata
Please guide.
Solution 1:[1]
I'm assuming that you want to collect all data to list or something like that, right?
Use the .append method, instead of just an assignment.
myfiles = []
all_files = glob.glob('D:/Master Thesis/MCDM Combined code/results/*.pkl')
for i, curr_file in enumerate(all_files):
with open(curr_file, 'rb') as f:
mydata = pickle.load(f)
if curr_file.find('1'):
myfiles.append(mydata)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
