2013-05-02 107 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 
>>> 
相關問題