0

I have a large number of files with data about specific dates but with random (ugly) names that I'd like to assign to a more structured string "infile" that I can then use to refer to the original filename. To be concrete, in the following code sample:

file_25Jan1995 = 'random_file_name_x54r'

year = '1995'
month = 'Jan'
day = '25'

infile = 'file_'+day+month+year   
print infile
print file_25Jan1995

This code produces the following output:

file_25Jan1995
random_file_name_x54r

My question is, how can I print (or pass to a function) the original filename directly through the newly created string "infile"? So I'd like "print some_method(infile)" to return "random_file_name_x54r". Is using a dict the only way to do this?

DJname
  • 667
  • 2
  • 6
  • 8
  • http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python is essentially the same question. – Neapolitan May 17 '16 at 02:16
  • Actually, you should consider changing the title. You are not asking about "plotting", but "printing". And actually you want the "variable name" instead of the "variable value". So, that part is reversed... – NichtJens May 17 '16 at 23:29

2 Answers2

1

Given that you have defined the variable, you can retrieve the value by name from locals:

print(locals()[infile])

or by using eval:

print(eval(infile))

You probably don't want to do this, though. Since you needed to make all the variables in the first place, you might as well put them in a dictionary.


One more suggestion... if you have the variables defined in a module, e.g., datasets.py, then you can fetch them from the module using getattr:

import datasets

print(getattr(datasets, infile))
Neapolitan
  • 2,101
  • 9
  • 21
  • Assuming he is looping over years or similar, what you proposed might do what he wants... BTW, you missed a brace in the first statement. – NichtJens May 17 '16 at 01:09
  • Fantastic, thank you, this does it! The style of notation, method()[argument], is new to me, and in particular I hadn't come across locals(). I was expecting something more like argument.method(). – DJname May 17 '16 at 01:16
  • The notation is doing two things at a time. `locals()` returns a dict, which is read-out via the brackets. Think of `localsdict=locals()` and `print localsdict[infile]` – NichtJens May 17 '16 at 23:25
0

Your question is very unclear. Are you simply looking for something like this:

def some_method(input):
    #do something to input
    return input

print some_method(infile)
NichtJens
  • 1,709
  • 19
  • 27
  • Sorry the way I posed the question wasn't very clear. Yes, I simply want the string that is the filename refer to its original value, instead of to the name of the string. I hope this makes sense. – DJname May 17 '16 at 00:59