将字符串传递给python中的文件打开函数

sbr*_*bru 1 python file-io python-2.x

我有一个用户输入,我想将它作为open函数的文件名参数传递.这是我尝试过的:

filename = input("Enter the name of the file of grades: ")
file = open(filename, "r")
Run Code Online (Sandbox Code Playgroud)

当用户输入openMe.py出现错误时,

NameError: name 'openMe' is not defined
Run Code Online (Sandbox Code Playgroud)

但是当用户输入"openMe.py"它工作正常.我很困惑为什么会这样,因为我认为文件名变量是一个字符串.任何帮助将不胜感激,谢谢.

Ash*_*ary 7

raw_input在Python 2中使用:

filename = raw_input("Enter the name of the file of grades: ")
Run Code Online (Sandbox Code Playgroud)

raw_input返回一个字符串,input相当于eval(raw_input()).

如何eval("openMe.py")工作:

因为python认为in openMe.py, openMe是一个对象while py是它的属性,所以它openMe首先搜索,如果没有找到则会引发错误.如果openMe找到,则会在此对象中搜索该属性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'
Run Code Online (Sandbox Code Playgroud)