Reputation: 636
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
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
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