简体   繁体   中英

Saving file with the name of the array variable Python

I am willing to save the file with the same name as the variable has. See teh following code:

training = np.arange(200)
np.savetxt(training.txt,training)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'txt'

When I use double quotes it will work as obvious:

np.savetxt("training.txt",training)

But in my program there are different variables and I want that when I call the file saving function the file name should automatically be taken as the variable name itself.
For example, if the variable is question , or answer , then when I say save() , the file name should automatically be question.txt or answer.txt
Suggest me what I can do to achieve this.

There is no good way this can work. A variable in Python is just a reference to the actual object. The name doesn't matter.

You need a way to store your variable with a given name, which is what associative tables are about, and that's a dict in Python.

This would resemble something like:

variables={}
variables["training"] = np.arange(200)
for key, val in variables.items():
    np.savetxt(key, value)

Working with identifier names in Python is cumbersome (and it is not intended to be a common practice). Why don't you try using a dictionary?

import np

my_dict = dict()

def save(name: str):
    np.savetext('{}.txt'.format(name), my_dict[name])

my_dict['training'] = np.arange(200)
save('training')

A very hackish way is to get the variable name from local symbol table. If you know that you have only one array, you can simple get the first result..

>>> 
>>> import numpy as np
>>> training = np.arange(200)
>>> def getndarrayname(env):
...     return list(filter(lambda x: isinstance(env[x], np.ndarray), env.keys()))
... 
>>> getndarrayname(locals())
['training']
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM