bagelboy bagelboy - 4 months ago 7
Python Question

passing string to file open function in python

I have a user input and I want to pass it as the file name parameter of the open function. This is what I have tried:

filename = input("Enter the name of the file of grades: ")
file = open(filename, "r")


When the user input is
openMe.py
an error arises,

NameError: name 'openMe' is not defined


but when the user inputs
"openMe.py
" it works fine. I am confused as to why this is the case because I thought the filename variable is a string. Any help would be appreciated, thanks.

Answer

Use raw_input in Python 2:

filename = raw_input("Enter the name of the file of grades: ")

raw_input returns a string while input is equivalent to eval(raw_input()).

How does eval("openMe.py") works:

Because python thinks that in openMe.py, openMe is an object while py is its attribute, so it searches for openMe first and if it is not found then error is raised. If openMe was found then it searches this object for the attribute py.

Examples:

>>> eval("bar.x")  # stops at bar only
NameError: name 'bar' is not defined

>>> eval("dict.x")  # dict is found but not `x`
AttributeError: type object 'dict' has no attribute 'x'