我有一个用户输入,我想将其作为打开函数的文件名参数传递。这是我尝试过的:
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
,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
.
例子:
>>> 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'
关于python - 将字符串传递给python中的文件打开函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332921/