Alex
Alex

Reputation: 636

How to save a list of variables whose names (as strings) are given?

So I have a bunch of numpy arrays, the names of which (as strings) are in a list:

mylist = ['arr1', 'arr2', ....]

I want to save them with np.save, all of them. What I tried:

for avar in mylist:
    np.save(avar+'.npy', exec(avar))

It works? IDK, at least there's no error, But, when later loaded, it throws this error:

ValueError: Object arrays cannot be loaded when allow_pickle=False

Would be nice if you show me how to load them later to same variable names.

Upvotes: 0

Views: 758

Answers (2)

fizzybear
fizzybear

Reputation: 1227

If all your variables are local, you can do

vars = locals()
for astring in mylist:
    np.save(astring + '.npy', vars[astring])

If you have some global variables as well, then do

vars = globals()

@Alex, if your variable names are coming in from the network or an external file, then you run the risk of arbitrary code execution with exec.

Upvotes: 1

Alex
Alex

Reputation: 636

I think I got it,

for astring in mylist:
    exec('tmp = ' + astring )
    np.save(astring + '.npy', tmp)

When restoring:

for astring in mylist:
    tmp = np.load(astring + '.npy')
    exec(astring ' =  tmp' )

Upvotes: 0

Related Questions