将参数名称作为字符串 - Python

时间:2016-08-23 21:04:15

标签: python glob

我有一个函数,它接受一个变量作为参数。该变量碰巧包含一个目录,同时还包含一堆txt文件。

我想知道是否有办法将该变量视为字符串?不是变量中的内容,只是变量的名称。 非常感谢!

import glob
import pandas as pd

variable_1 = glob.glob('dir_pathway/*txt')
variable_2 = glob.glob('other_dir_pathway/*txt')

def my_function(variable_arg):
    ## a bunch of code to get certain things from the directory ##
    variable_3 = pd.DataFrame( ## stuff taken from directory ## )
    variable_3.to_csv(variable_arg + "_add_var_to_me.txt")

1 个答案:

答案 0 :(得分:2)

虽然这是非常奇怪的请求,但这里是你如何从函数

中获取参数的名称
import inspect

def f(value):
    frame = inspect.currentframe()
    print(inspect.getargvalues(frame)[0][0])

f(10)
f("Hello world")
f([1, 2, 3])

打印

value
value
value