2012-07-10 24 views
1

我寫一些代碼,需要用戶輸入一個文件在程序中使用:輸入數據沒有定義

file=input('input file name') 
然而

,當你再輸入一個文件名(或任何爲此事)的錯誤會彈出說什麼剛纔輸入的內容沒有被定義並結束程序。是什麼導致了這種情況發生?

謝謝

+0

複製錯誤?你如何試圖使用變量「文件」? – Dubslow 2012-07-10 11:34:42

回答

2

這一點很重要:

input([prompt]) -> value 
Equivalent to eval(raw_input(prompt)). 

輸入將嘗試eval您輸入

入住這

In [38]: l = input("enter filename: ") 
enter filename: dummy_file 
--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
C:\Python27\<ipython-input-37-b74d50e2a058> in <module>() 
----> 1 l = input("enter filename: ") 

C:\Python27\<string> in <module>() 

NameError: name 'dummy_file' is not defined 


In [39]: input /? 
Type:  builtin_function_or_method 
Base Class: <type 'builtin_function_or_method'> 
String Form:<built-in function input> 
Namespace: Python builtin 
Docstring: 
input([prompt]) -> value 

Equivalent to eval(raw_input(prompt)). 

In [40]: file = raw_input("filename: ") 
filename: dummy_file 

In [41]: file 
Out[41]: 'dummy_file' 

使用raw_input有它的缺點,但。

0

您需要使用raw_input而不是輸入。

輸入docsting:

輸入([提示]) - >值

相當於EVAL(的raw_input(提示))。

python解釋器會嘗試評估您的輸入,如果它是文件名,將會失敗。

0

input評估它的參數,所以當你給它類似​​它會嘗試把它作爲一個變量。改爲使用raw_input

(此外,使用file作爲變量名是一個壞主意,因爲它也是一個Python的名字內置類。喜歡的東西一樣pathfilenamef

4

如果你使用Python 2.x - 你想使用raw_input - input用於2.x中完全不同的東西。如果您使用Python 3.x - input是正確的。

在一個側面說明,推薦風格指南是使用open打開文件,所以它不是太糟糕了你的陰影file這裏,但任何人都期待能夠使用file(基本相同open)作爲一個函數可能會在稍後發生衝擊。

+1

+1解釋爲什麼raw_input – Dubslow 2012-07-10 11:48:03

相關問題