我有一个用户输入,我想将其作为打开函数的文件名参数传递。这是我尝试过的:
filename = input("Enter the name of the file of grades: ")
file = open(filename, "r")
当用户输入的是openMe.py
出现错误,
NameError: name 'openMe' is not defined
但是当用户输入"openMe.py
“它工作正常。我很困惑为什么会出现这种情况,因为我认为文件名变量是一个字符串。任何帮助将不胜感激,谢谢。
Use raw_input
在Python 2中:
filename = raw_input("Enter the name of the file of grades: ")
raw_input
返回一个字符串input
相当于eval(raw_input())
.
如何eval("openMe.py")
works:
因为Python认为在openMe.py
, openMe
是一个对象,同时py
是它的属性,所以它搜索openMe
首先,如果是的话
未找到则引发错误。如果openMe
被发现然后搜索
this 对象的属性py
.
例子:
>>> 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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)