简体   繁体   English

使用数组变量Python的名称保存文件

[英]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 例如,如果变量是questionanswer ,那么当我说save() ,文件名应自动为question.txtanswer.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. Python中的变量只是对实际对象的引用。 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. 你需要一种方法来你的变量存储与给定的名称,这是关联表是一下,这是一个dict 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). 在Python中使用标识符名称很麻烦(并且不打算作为惯例)。 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']
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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