2015-10-20 41 views
0

我試圖提示用戶輸入要讀取的文件,如果在目錄中找不到該文件,它將打印一條消息,然後重新提示用戶。對於錯誤處理,我嘗試使用Try和Except語句,並嘗試用while循環對其進行循環。請幫助,爲什麼不工作!嘗試和除了while循環內部 - 打開文件

while True: 

    try: 
     input_file = input('Enter the name of the Input File: ') 
     ifile = (input_file, 'r') 
     continue 

    except: 
     print('File not found. Try again.') 
+0

'continue'檢查在一個循環中的最後一條語句是多餘的。它沒有效果。 – melpomene

+1

你不會在任何地方打開文件。 – melpomene

+0

@ C.Slates收到一個有效的文件名稱,你需要打破的外觀使用'break'而不是'繼續' – shanmuga

回答

1

它會更有意義與os.path.isfile

import os 

while True: 

    input_file = input('Enter the name of the Input File: ') 
    if not os.path.isfile(input_file): 
     print('File not found. Try again.') 
     continue 
    break 

print('File found!')