Search code examples
pythondictionaryfor-loopinstance-variables

Is there a way to turn list elements into independent variables while referencing the original list?


I want to take all the files of one type (.npy) from a directory and turn them into named variables that call the data from the .npy file using np.load from numpy.

I've used glob to create a list of files of one type, however I can seem to find a good way to proceed.

os.chdir("/Users/Directory/")
dir_path = os.getcwd()

file_names = sorted(glob.glob('*.npy'))
file_names = file_names[:]
for f in file_names:
    print(f)
EELS 10nmIF 16nm.npy
EELS 4nmIF 16nm.npy
EELS Background.npy

What I want the output to be is a set of variables with the names:

EELS 10nmIF 16nm
EELS 4nmIF 16nm
EELS Background

And each variable would call the data from the .npy file such using np.load such that essentially it would look like this:

EELS 10nmIF 16nm = np.load(dir_path + EELS 10nmIF 16nm.npy)
EELS 4nmIF 16nm = np.load(dir_path + EELS 4nmIF 16nm.npy)
EELS Background = np.load(dir_path + EELS Background.npy)

Solution

  • You can use a list comprehension to create a new list of trimmed file names.

    variables = [f[0:-4] for f in file_names]
    

    Then you can do anything you want with the contents of this list, including load each of the files:

    for v in variables:
        np.load(dir_path + v + '.npy')
    

    Alternatively, skip the above steps and just load in all the files directly:

    for f in file_names:
        np.load(dir_path + f)
    

    I may be missing the point of your question though, so perhaps this answer has what you need.