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?

2
  • stackoverflow.com/questions/1373164/… is essentially the same question. Commented May 17, 2016 at 2: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... Commented May 17, 2016 at 23:29

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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().
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]
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)

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.