Python try / catch如果无法打开文件

时间:2017-09-19 01:03:46

标签: python python-2.7

下面是一个简单的程序,用于读取文件并读取文件中有多少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声明中这样做?

1 个答案:

答案 0 :(得分:0)

在try / except语句中,可能失败的代码进入try部分,同时在except部分发生异常时应该运行的代码。

try:
    myfile = open(filename)
except IOError as E:
    print 'File Not Found'