2016-11-18 38 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)