-1

Possible Duplicate:
python obtain variable name of argument in a function

I have the following code which creates a file list.txt,currently i hard-code the filename as 'list.txt',is there a way we can create the filename dynamically based on the argument name passed to the function Eg..list is passed as argument here in this example,so file name should be list.txt,if the parameter is list2.txt,file name should be list2.txt .....

def filecreation(list):
    #print "list"
    with open('list.txt', 'w') as d:
        d.writelines(list)

def main():
    list=['206061\n', '202086\n', '206062\n']
    filecreation(list)

if __name__ == '__main__':
    main()
Community
  • 1
  • 1
user1927233
  • 151
  • 1
  • 2
  • 11

2 Answers2

7

Could you do something like:

def filecreation(alist, filename):
    #print "alist"
    with open(filename, 'w') as d:
        d.writelines(alist)

With this, you could call something like filecreation(list, "testfile.txt"), and it would output your list into testfile.txt. If I'm misunderstanding let me know and I'll try to fix it.

martineau
  • 119,623
  • 25
  • 170
  • 301
Michael Oliver
  • 1,392
  • 8
  • 22
3

The function can't know what the variable passed as argument was called. That's just not how Python works. There might even not be any variable involved:

filecreation(['206061\n', '202086\n', '206062\n']) # What is the argument "name"?

The closest you can get to what you want is the linked question Ignacio Vazquez-Abrams posted in the comments, so I'd suggest taking a look at that.

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • 1
    Not strictly true. I bet you could inspect the interpreter stack and figure it out in some cases. But, point taken. – Phil Frost Dec 31 '12 at 19:24