2011-01-11 85 views
0

我使用python 2.6.6,但無法解決我的問題。如果條件未驗證,Python會創建一個循環

我有這樣的代碼:

file = raw_input('Enter the name of the file: ') 
try: 
    text_file = open(file,'r') 
except IOError: 
    print 'File not found' 
    file = raw_input('Enter the name of the file: ') 
    text_file = open(file,'r') 

我怎麼能變成一個循環這個,這樣,如果用戶輸入了錯誤的文件名或文件它無法在該位置它將繼續要求的文件嗎?

問候,

Favolas

回答

7
while True: 
    file = raw_input('Enter the name of the file: ') 
    try: 
     text_file = open(file,'r') 
     break 
    except IOError: 
     print 'File not found' 
+0

感謝斯文。在來這裏之前,我已經完成了與您發佈的代碼完全相同的代碼,但沒有中斷,這給我帶來了錯誤。需要練習更多:) – Favolas 2011-01-11 15:51:40