下面是一个读取文件和读取文件中有多少个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语句中有没有这样的方法?你知道吗
在try/except语句中,可能失败的代码放在
try
部分,而发生异常时应该运行的代码放在except
部分。你知道吗相关问题 更多 >
编程相关推荐