Python基础学习_文件与异常_异常
1.3异常的出现的原因:Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。
即一出现异常,python都会创建一个异常对象
异常处理的模块: try-except,作用让pyhthon执行指定的操作,
同时告知python出现错误该怎么办
好处:即使出现异常,程序也将继续运行,显示你编写的友好的错误消息,
而不至于令编程者在traceback上迷糊
1.3.1 处理ZeroDivisionError异常
ZeroDivisionError: division by zero,程序报的错误
ZeroDivisionError是一个异常对象,python无法执行,即返回ZeroDivisionError对象
于是停止运行,然后我们按照原因去修改代码块
print(5/0)
结果:
Traceback (most recent call last):
File "<ipython-input-6-fad870a50e27>", line 1, in <module>
print(5/0)
ZeroDivisionError: division by zero
解释:因为0位不能为分母,因为0不能为被除数,所以报错
1.3.2 使用try-except 代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
结果:
You can't divide by zero!
解释:加上try-except模块后直接告诉你错误的原因是0不能为分母,而不是Traceback
注意: 若try 代码块中的代码运行起来没问题,则跳过except代码
否则,执行except代码,python会查找这样的except代码块,并运行其中的代码
即其中指定的错误与引发的错误相同,如try-except后面还有代码,则继续运行
10.3. 使用异常避免崩溃
只执行简单除法的计算器
print("Give me too numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
if second_number == 'q':
break
answer = int(first_number) / int(second_number)
print(answer)
结果:
例子1: 5,6
Give me too numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 6
0.8333333333333334
First number: q
例子2:
Give me too numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
Traceback (most recent call last):
File "<ipython-input-9-132a63a48014>", line 11, in <module>
answer = int(first_number) / int(second_number)
ZeroDivisionError: division by zero
使用异常对象的原因:只展示出现异常的对象,即是后面answer = int(first_number) / int(second_number)这句话不应该展示出来,避免让黑客知道程序容易出错的位置,而应该只展示ZeroDivisionError: division by zero
而不展示出现异常的代码块,这样有利于不被黑客攻击
1.3.4 else 代码块
将有可能引发错误的代码放在try-except代码块中,可以提高程序抵御错误的能力
print("Give me too numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
结果:
例子1:9,6
Give me too numbers, and I'll divide them.
Enter 'q' to quit.
First number: 9
Second number: 6
1.5
First number: q
例子2:
Give me too numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by 0!
First number: q
更改后的代码就隐藏掉我们容易被黑客入侵的漏洞程序
try-except-else代码块的运行原理:当try后面的代码执行正确时跳过except代码块,
执行else语句后面的代码块;当try后面的代码执行不通过时,执行except后面的代码抛出错误
注意:try代码块里面放的是能引发错误的代码块,else代码块放的是try代码块能执行时
相应的其他代码块
1.3.5 处理FileNotFoundError异常
即,找不到文件错误
filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read()
结果:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
错误提示:FileNotFoundError: [Errno 2] No such file or directory: ‘alice.txt’
即找不到名为alice.txt的文件
这个错误是函数open()导致的,因此处理这个错误将try放在open()的代码前面
好处:显示友好的错误信息,即文件不存在,而不是traceback
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file" + filename + "does not exist."
print(msg)
else:
print(contents)
结果:
Sorry, the filealice.txtdoes not exist.
1.3.6 分析文本文件
使用多个文件,异常处理的好处
split()方法:根据字符串创建一个单词列表,即拆分字符串
拆分方式:以空格符将字符串拆成多个部分,并将多个部分放到一个列表中
用途:拆分小说,计算列表的元素多少,最终知道有多少个单词
title = 'Alice in Wonderland'
title.split()
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file" + filename + "does not exist."
print(msg)
else:
# 计算文件大致包含多少个单词
words = contents.split() # 以空格符拆分 返回单词列表
num_words = len(words) # 统计元素数量
print("The file " + filename + " has about " + str(num_words) + ' words.')
结果:
The file alice.txt has about 29461 words.
1.3.7 使用多个文件
分析多本书
# 定义 count_words()函数
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# 计算文件大致包含多少个单词
words = contents.split() # 以空格符拆分 返回单词列表
num_words = len(words) # 统计元素数量
print("The file " + filename + " has about " + str(num_words) + ' words.')
## 修改程序的同时更新注释是好的习惯
filename = 'alice.txt'
count_words(filename)
统计不同书本的单词数
filenames = ['alice.txt','siddhartha1.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
结果:
The file alice.txt has about 29461 words.
The file alice.txt has about 29461 words.
Sorry, the file siddhartha1.txt does not exist.
The file moby_dick.txt has about 215136 words.
The file little_women.txt has about 189079 words.
解释:可以看到除了第3行一外,其他都正常的显示了每个文本中单词数目;而第三个文本不存在,直接给了用户提示,方便用户去检查用户输入的文件名称是否正确。
1.3.8 失败时一声不吭
即在except代码块中 用pass直接什么都不做,pass还充当占位符
占位符:即目前不做什么,但是后面我们可以加一个将异常问题写入一个文本文件
中以备后期维护
# 定义 count_words()函数
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# 计算文件大致包含多少个单词
words = contents.split() # 以空格符拆分 返回单词列表
num_words = len(words) # 统计元素数量
print("The file " + filename + " has about " + str(num_words) + ' words.')
统计不同书本的单词数
filenames = ['alice.txt','siddhartha1.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
结果:
The file alice.txt has about 29461 words.
The file moby_dick.txt has about 215136 words.
The file little_women.txt has about 189079 words.