2011-01-11 83 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