2013-05-02 79 views
1

我有一个用户输入,我想将它作为打开函数的文件名参数传递。这是我曾尝试:将字符串传递给Python中的文件打开函数

filename = input("Enter the name of the file of grades: ") 
file = open(filename, "r") 

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

NameError: name 'openMe' is not defined 

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

回答

7

使用raw_input在Python 2:

filename = raw_input("Enter the name of the file of grades: ") 

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

如何eval("openMe.py")作品:因为Python认为在openMe.pyopenMe是一个对象,而 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' 
+0

等等。简单。谢谢 – sbru 2013-05-02 07:54:15

+1

为什么eval(“openMe.py”)去掉.py? – Sarien 2013-05-02 07:57:04

+0

@Sarien因为python认为在'openMe.py'中,'openMe'是一个对象,而'py'是它的属性,所以它首先搜索'openMe',如果找不到则会引发错误。 – 2013-05-02 08:02:13

1

正如阿什维尼说,你必须在Python 2.x中使用raw_input因为input被视为基本eval(raw_input())

为什么input("openMe.py")出现剥离.py末的原因是因为蟒蛇试图找到所谓openMe一些对象,并访问它的属性.py

>>> 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 
>>> 
相关问题