0

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.

  • 3
    You have this problem because your approach is incorrect: Collect your "different variables" into a Python dictionary (`dict`), then the variable names are dictionary keys, i.e. ordinary strings, and you can use them to construct filenames. – alexis Jan 29 '19 at 10:48
  • 1
    Something like [this](https://stackoverflow.com/a/18425523/4121573) might work, but I'd not recommend this approach – Adonis Jan 29 '19 at 10:50
  • 1
    Possible duplicate of [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – Thierry Lathuille Jan 29 '19 at 10:56
  • You might want to look into `numpy.savez` ( https://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html ) to save many array objects into the same file. – Learning is a mess Jan 29 '19 at 10:57

3 Answers3

3

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)
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • 1
    I have to disagree, you can make it work with `inspect` with all the dangers that come with it of course – Adonis Jan 29 '19 at 10:51
  • @Adonis basically, you are hacking the variable system to get exactly the same, except that you won't be able to figure out which variable you actually want anyway. So no, `inspect` will not work properly either. How do you know which variables need to be saved? – Matthieu Brucher Jan 29 '19 at 10:53
  • In function if I pass the variable, then will the inspect work? I am looking at it. – Amazing Things Around You Jan 29 '19 at 10:55
  • 2
    You have a dictionary, so you will have to check which variables is the same as your variable, and the have the name. But that's fragile, and not a sound approach. The proper Pythonic way is to store the data with its name in a dictionary. After all, the local variables are a dictionary, you are just exposing and being explicit about what you do, which is the Python way. – Matthieu Brucher Jan 29 '19 at 10:58
  • @Adonis I liked your idea. – Amazing Things Around You Jan 29 '19 at 11:01
  • @MatthieuBrucher May be I am not right the Pythonic way, but there has to have some way outside the way the world is doing. Adonis gave a good suggestion. I liked your answer too. – Amazing Things Around You Jan 29 '19 at 11:02
  • 1
    Personally, if one of my team members writes code using `inspect` for such a case, I'm refusing his code. – Matthieu Brucher Jan 29 '19 at 11:03
  • 1
    @AmazingThingsAroundYou Mathieu is right, and my idea is absolutely not a good one, just a possibility that I'd highly discourage, except to have some fun with Python's inner working – Adonis Jan 29 '19 at 11:04
  • Thank you all for your answers and enlightening words. – Amazing Things Around You Jan 29 '19 at 11:06
  • Agreed, it's good sometimes to explore Python internals as well ;) – Matthieu Brucher Jan 29 '19 at 11:08
1

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')
Anakhand
  • 2,838
  • 1
  • 22
  • 50
0

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']
>>> 
vin
  • 960
  • 2
  • 14
  • 28
  • Not a right way, as it gives me a list of all the variables I am using. `['traning', 'data', 'data_slice', 'training']`, Now you could imagine. – Amazing Things Around You Jan 29 '19 at 11:04
  • Hehe, so this is not the answer for you. Maybe you could create one array in one function, so that only one array gets created in local scope... – vin Jan 29 '19 at 11:06