2016-11-18 28 views
0

我正在創建一個程序,要求用戶選擇一個文件在程序中運行,但我不能停止程序崩潰時不存在的文件名稱被輸入。我嘗試過嘗試語句和for循環,但他們都給出了一個錯誤。我有選擇的文件中的代碼如下:不能停止程序崩潰用戶輸入的錯誤文件

data = [] 
print "Welcome to the program!" 
chosen = raw_input("Please choose a file name to use with the program:") 
for line in open(chosen): 
    our_data = line.split(",") 

    data.append(our_data) 
+0

請說明您是如何嘗試'try'語句的。這是做到這一點的正確方法。 –

+0

'try'在這裏是正確的解決方案。向我們展示您使用它的代碼。 –

回答

0

RTM

import sys 

try: 
    f = open('myfile.txt') 
    s = f.readline() 
    i = int(s.strip()) 
except IOError as e: 
    print "I/O error({0}): {1}".format(e.errno, e.strerror) 
except ValueError: 
    print "Could not convert data to an integer." 
except: 
    print "Unexpected error:", sys.exc_info()[0] 
    raise 
3

添加例外:

data = [] 
print "Welcome to the program!" 
chosen = raw_input("Please choose a file name to use with the program:") 
try: 
    for line in open(chosen): 
     our_data = line.split(",") 

     data.append(our_data) 
except IOError: 
     print('File does not exist!') 
2

不使用異常,你可以簡單地檢查文件是否存在,如果沒有再次要求。

import os.path 

data = [] 
print "Welcome to the program!" 
chosen='not-a-file' 
while not os.path.isfile(chosen): 
    if chosen != 'not-a-file': 
     print("File does not exist!") 
    chosen = raw_input("Please choose a file name to use with the program:") 
for line in open(chosen): 
    our_data = line.split(",") 

    data.append(our_data) 
相關問題