2015-10-20 39 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!')