Python – How do I use my array name as a filename?

How do I use my array name as a filename?… here is a solution to the problem.

How do I use my array name as a filename?

My code is doing some math and saving the output in multiple NumPy arrays.

Finally, I

write the output to disk, for which I want to use the names of the arrays as separate file names, to which each array will be written.

For example, if I have the following multidimensional array

time = [...]
force = [...]
pressure = [...]
energy = [...] 

Wait, me too

for array in [time, force, pressure, energy, ....]:
    with open(**filename**, 'w') as file:
         pickle.dump(array, file)

But how to set the file name so that it takes an array name.

I’ve experienced many similar issues (albeit with other motives). The answer indicates that the array (or any variable) name is just a label, not retrieved like this. But my motivation for naming the file here seems to be a real need (at least for me), so ask. If possible, I might be able to write more advanced in HDF5 format and use the array names as different datasets. While all of this can be done manually, why should we code?

Solution

If I create a list from a set of variables, I won’t be able to retrieve the names of those variables. I can only retrieve objects that reference variables.

In [324]: x = np.arange(3)
In [325]: y = np.ones((3,3))
In [326]: alist = [x,y]
In [327]: alist
Out[327]: 
[array([0, 1, 2]), array([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])]
In [328]: id(x)
Out[328]: 2851921416
In [329]: id(alist[0])
Out[329]: 2851921416

alist[0] does not refer to the variable name “x” in any way.

Dictionaries are a better way to associate names or strings with objects:

In [331]: adict = {'x':x, 'y':y}
In [332]: adict['x']
Out[332]: array([0, 1, 2])

With such a dictionary, I can save these arrays in savez:

In [334]: np.savez('temp', **adict)
In [336]: d = np.load('temp.npz')
In [337]: list(d.keys())
Out[337]: ['y', 'x']

The npz archive contains two files named :

In [340]: !unzip -l temp.npz
Archive:  temp.npz
  Length      Date    Time    Name
---------  ---------- -----   ----
      200  2018-01-29 23:58   y.npy
      140  2018-01-29 23:58   x.npy
---------                     -------
      340                     2 files

The dictionary is also useful when creating HDF5 datasets.

Some examples of using pickle to save/load variables (and dictionaries):

How to load/view structure of pickled object in Ipython console ? (Windows 7, Spyder, Ipython console)

Here’s an attempt to save and load a workspace (or part of it), just as you typically do with MATLAB:

IPython loading variables to workspace: can you think of a better solution than this?

IPython: how to automagically load npz file and assign values to variables?

Related Problems and Solutions