我正在创建一个程序,要求用户选择要在程序中运行的文件,但是当输入不存在的文件名时,我无法阻止程序崩溃。我尝试过try语句和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 :(得分: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!')
答案 1 :(得分: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)
答案 2 :(得分:0)
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