下面是一个简单的程序,用于读取文件并读取文件中有多少8个文件:
import sys
if len(sys.argv) == 1:
print "ERROR: Please put a filename after your Python file!"
else:
myFile = sys.argv[1]
new = open(myFile)
numEight = 0
text = new.read()
line = len(text.splitlines())
for char in text:
if char == "8":
numEight = numEight + 1
print "There are ", numEight, "in this text file"
问题是,如果输入的文件名不正确,如何创建try catch?或者,有没有办法在elif声明中这样做?
答案 0 :(得分:0)
在try / except语句中,可能失败的代码进入try
部分,同时在except
部分发生异常时应该运行的代码。
try:
myfile = open(filename)
except IOError as E:
print 'File Not Found'