Plot variable value instead of name in Python
Question: 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?


Answer: 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))
    

