Python try/catch如果无法打开fi

2024-09-28 04:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个读取文件和读取文件中有多少个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语句中有没有这样的方法?你知道吗


Tags: 文件textinimport程序newlenif
1条回答
网友
1楼 · 发布于 2024-09-28 04:20:04

在try/except语句中,可能失败的代码放在try部分,而发生异常时应该运行的代码放在except部分。你知道吗

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

相关问题 更多 >

    热门问题