How to open multiple pickle files in a folder

Viewed 534

I have multiple pickle files with the same format in one folder called pickle_files:

1_my_work.pkl
2_my_work.pkl
...
125_my_work.pkl

How would I go about loading those files into the workspace, without having to do it one file at a time?

Thank you!

1 Answers

Loop over the files and save the data in a structure, for example a dictionary:

# Imports
import pickle
import os

# Folder containing your files
directory = 'C://folder'

# Create empty dictionary to save data
data = {}

# Loop over files and read pickles
for file in os.listdir(directory):
    if file.endswith('.pkl'):
        with open(file, 'rb') as f:
            data[file.split('.')[0]] = pickle.load(f)

# Now you can print 1_my_work
print(data['1_my_work'])
Related