我有一个用户输入,我想将其作为打开函数的文件名参数传递。这是我尝试过的:
filename = input("Enter the name of the file of grades: ")
file = open(filename, "r")
当用户输入openMe.py时,会出现错误,
NameError: name 'openMe' is not defined
但是当用户输入 "openMe.py"时它工作正常。我对为什么会这样感到困惑,因为我认为文件名变量是一个字符串。任何帮助将不胜感激,谢谢。
请您参考如下方法:
在 Python 2 中使用 raw_input:
filename = raw_input("Enter the name of the file of grades: ")
raw_input 返回一个字符串,而 input 等同于 eval(raw_input())。
eval("openMe.py") 是如何工作的:
Because python thinks that in
openMe.py,openMeis an object whilepyis its attribute, so it searches foropenMefirst and if it is not found then error is raised. IfopenMewas found then it searches this object for the attributepy.
例子:
>>> 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'
