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.
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 whilepy
is its attribute, so it searches foropenMe
first and if it is not found then error is raised. IfopenMe
was found then it searches this object for the attributepy
.
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'
As Ashwini said, you must use raw_input
in python 2.x because input
is taken as essentially eval(raw_input())
.
The reason why input("openMe.py")
appears to strip the .py
at the end is because python attempts to find some object called openMe
and access it's .py
attribute.
>>> openMe = type('X',(object,),{})() #since you can't attach extra attributes to object instances.
>>> openMe.py = 42
>>> filename = input("Enter the name of the file of grades: ")
Enter the name of the file of grades: openMe.py
>>> filename
42
>>>
来源:https://stackoverflow.com/questions/16332921/passing-string-to-file-open-function-in-python