1

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)
Goose
  • 25
  • 1
  • 4

2 Answers2

1

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.

  • Thank you for the suggestion. I think that this answer is close to the answer, however what I am looking for is a results where 'EELS 10nmIF 16nm.npy' becomes a variable that I could call such that [EELS 10nmIF 16nm] would give display the array of data contained by the variable. – Goose Apr 22 '19 at 20:57
  • How do you plan on calling the variables? One at a time on the command line, for example, or elsewhere in your script? A bit more info on why you need to manually load the files by their names would help. – Tyler Quiring Apr 23 '19 at 16:06
0

I‘m not 100% sure but i think you can‘t assign variable names at runtime in python (or any other language i know of), but what you can do is using a dictionary which has the filenames as key and then use an object as value that contains the data from the files

RomanHDev
  • 104
  • 5
  • on second thought you actually can do this in python by picking up and manipulating the AST of your code. But that would completely defeat the purpose of what you are trying to do – RomanHDev Apr 18 '19 at 18:03
  • This is indeed possible in many languages, and even in python you may do `globals()["foo"]="bar"` to assign global variable `foo`. Though, variables with white spaces within names are not allowed in python. – Mikhail Vladimirov Apr 18 '19 at 18:03