异常
- 使用被称为异常的特殊对象来管理程序执行期间发生的错误。
- 每当发生python不知所措的错误时,都会创建一个异常对象。
- 编写处理该异常的代码,程序将继续执行。
- 如果未对异常做出处理,程序将停止,并显示一个traceback。
- 使用try-except代码块处理异常
处理ZeroDivisionError异常
print(5/0)
Traceback (most recent call last):
File "D:\学习笔记\python学习笔记\第十章\division.py", line 6, in
print(5/0)
ZeroDivisionError: division by zero
[Finished in 0.1s with exit code 1]
使用try-except代码块
- 编写一个try-except代码块来处理可能引发的异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero")
You can't divide by zero
[Finished in 0.3s]
使用异常避免崩溃
print("Give me two number,and I'll divide them.")
print("Enter q to quit.")
while True:
first_number = input("\n First number: ")
if first_number == 'q':
break
second_number = input("\n Second number" )
if second_number == 'q':
break
answer = int(first_number)/int(second_number)
print(answer)
Give me two number,and I'll divide them.
Enter q to quit.
First number: 10
Second number3
3.3333333333333335
First number: 5
Second number0
Traceback (most recent call last):
File "division.py", line 20, in
answer = int(first_number)/int(second_number)
ZeroDivisionError: division by zero
***Repl Closed***
else代码块
- 将可能发生的错误放在try-except代码块中,依赖于try代码块成功执行的代码都应该放在else代码块中。
print("Give me two number,and I'll divide them.")
print("Enter q to quit.")
while True:
first_number = input("\n First number: ")
if first_number == 'q':
break
second_number = input("\n Second number" )
if second_number == 'q':
break
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divide by 0.")
else:
print(answer)
Give me two number,and I'll divide them.
Enter q to quit.
First number: 10
Second number3
3.3333333333333335
First number: 5
Second number0
You can't divide by 0.
First number: q
***Repl Closed***
- try-except-else代码块的工作原理。python尝试执行try代码块中的代码,在try代码成功执行的运行代码放在else中,try代码引发异常的放在excepy中。
处理FileNotFoundError异常
- 读取一个不存在的文件
filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read()
Traceback (most recent call last):
File "D:\学习笔记\python学习笔记\第十章\alice.py", line 2, in
with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
[Finished in 0.3s with exit code 1]
- 这个错误时open()函数导致的,所以try语句放在包含open()的代码之前
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
mes = "Sorry, the file " + filename + "does net exist"
print(mes)
Sorry, the file alice.txtdoes net exist
[Finished in 0.4s]
分析文本
- 使用方法split(),根据一个字符创创建一个单纯列表。
>>> title = "alice in wonderland"
>>> title.split()
['alice', 'in', 'wonderland']
- 方法split()以空格为分隔符将字符串拆分成多个部分。将这些部分都存储在列表中。
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
mes = "Sorry, the file " + filename + "does net exist"
print(mes)
else:
word = contents.split()
num_word = len(word)
print("The file " + filename + "has about " + str(num_word) + " words.")
The file alice.txthas about 29461 words.
[Finished in 0.1s]
使用多个列表
- 将这个程序中的大部分代码移到一个名为count_words()的函数中。
def count_word(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
mes = "Sorry, the file " + filename + "does net exist"
print(mes)
else:
word = contents.split()
num_word = len(word)
print("The file " + filename + "has about " + str(num_word) + " words.")
filename = 'alice.txt'
count_word(filename)
The file alice.txthas about 29461 words.
[Finished in 0.1s]
- 编写简单的循环,分析文本里包含的单词
def count_word(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
mes = "Sorry, the file " + filename + "does net exist"
print(mes)
else:
word = contents.split()
num_word = len(word)
print("The file " + filename + "has about " + str(num_word) + " words.")
books = ['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt']
for book in books:
count_word(book)
The file alice.txthas about 29461 words.
The file siddhartha.txthas about 42172 words.
The file moby_dict.txthas about 215136 words.
Sorry, the file little_women.txtdoes net exist
[Finished in 0.4s]
失败时一声不吭
- 使用pass语句,可以在代码块中使用告诉python什么都不要做。
def count_word(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
# mes = "Sorry, the file " + filename + "does net exist"
# print(mes)
pass
else:
word = contents.split()
num_word = len(word)
print("The file " + filename + "has about " + str(num_word) + " words.")
books = ['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt']
for book in books:
count_word(book)
The file alice.txthas about 29461 words.
The file siddhartha.txthas about 42172 words.
The file moby_dict.txthas about 215136 words.
[Finished in 0.3s]
- pass语句充当占位符,提醒你在程序的某个地方什么都没做。
决定报错哪里错误
决定什么时候向用户报告错误?什么情况下又应该在失败时一声不吭那。
编写好的代码且经过详细测试的,不容易出现内部错误,如语法和逻辑错误。
但是只要程序依赖外部因素,如用户输入,存在指定的文件,有网络连接,有可能出现异常。
凭经验判断该在什么地方包含异常处理模块,以及出现错误时该向用户提供什么样的信息。
存储数据
- 使用模块json来存储数据。
- 模块json可以将简单的python数据结构存储在文件里,并在程序再次运行时加载该文件中的数据。
- 使用json在python程序直接分享数据。
- json并非python专用的,可以将json格式存储的数据与其他编程语言的人共享。
- JSON(Javascript Object Notation),最初视为JavaScript设计的,后来成为一种常用格式
使用json.dump()和json.load()
- 使用json.dump()来存储这组数字。
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as file_object:
json.dump(numbers,file_object)
- numbers.json文件显示
[2, 3, 5, 7, 11, 13]
- 函数json.dump()结束两个实参,要存储的数据,以及要存储数据的文件对象。
- 使用jsom.load()将这个列表读取到内存中。
import json
filename = 'numbers.json'
with open(filename) as file_object:
numbers = json.load(file_object)
print(numbers)
[2, 3, 5, 7, 11, 13]
[Finished in 0.3s]
- 使用函数json.load()加载存储咋number.json的信息,然后将其存储在变量numbers
保存和读取用户生产的数据
- 对于用户生产的数据,使用json保存很有用。
- 如果不以某种形式进行存储,等程序停止运行时用户的信息会丢失。
- 存储用户的名字
import json
username = input("What is your name? ")
filename = 'username.json'
with open(filename,'w') as file_object:
json.dump(username,file_object)
print("We'll remember you when you come back, " + username + '.')
What is your name? alice
We'll remember you when you come back, alice.
***Repl Closed***
- username.json
"alice"
- 在编写一个程序,向其名称被存储的用户发出问候
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back " + username + '!')
Welcome back alice!
[Finished in 0.2s]
- 将两个程序合并到一个程序。
import json
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileExistsError:
username = input("What is your name? ")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back, " + username + ".")
else:
print("Welcome back, " + username)
Welcome back, alice
[Finished in 0.1s]
重构
- 代码能够正确运行,但是可以做进一步改进
- 将代码划分成一系列具体完成工作的函数,这样的过程叫做重构。
- 重构让代码更清晰,更易于理解,更容易拓展。
- 将所有的代码放在greet_user()的函数中。
import json
def greet_user():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileExistsError:
username = input("What is your name? ")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back, " + username + ".")
else:
print("Welcome back, " + username)
greet_user()
Welcome back, alice
[Finished in 0.4s]
- 重构greet_user(),将获取用户名的代码转移到另一个函数中。
import json
def get_stored_username():
"""如果存储了用户就获取他"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileExistsError:
return None
else:
return username
def greet_user():
"""问候用户并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back " + username + ".")
else:
username = input("What is your name? ")
filename = 'username.json'
with open(filename,"w") as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back, " + username + ".")
greet_user()
Welcome back alice.
[Finished in 0.2s]
- 将greet_user的另一个代码提取出来。
import json
def get_stored_username():
"""如果存储了用户就获取他"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileExistsError:
return None
else:
return username
def get_new_user():
"""提示用户输入用户名"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json,dump(username,f_obj)
return username
def greet_user():
"""问候用户并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back " + username + ".")
else:
username = get_new_user()
print("We'll remember you when you come back, " + username + ".")
greet_user()
Welcome back alice.
[Finished in 0.2s]
小结
- 如何使用文件
- 如何一次性读取文件,
- 每次一行的方式读取文件
- 如何写入文件,如何将文件附加到文件的尾行
- 什么是异常,以及如何处理异常
- 如何存储python的数据结构,以及保存用户存储的信息 。