异常
1.1 使用try-except代码块
try: #如果try代码块中没有问题,python将跳过except代码块
print(5/0)
except ZeroDivisionError: #try代码块中引发异常,将执行except代码块
print("You can't divide by zero!")
结果:
You can't divide by zero!
1.2 使用异常避免崩溃
print("Give me two 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("Second_number: ")
try:
answer=int(first_number)/int(second_number) #只有可能引发异常的代码块才需要放在try语句中
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer) #else中执行成功的代码块
结果:
1.3 处理FileNotFoundError异常
file_name='alice.txt'
try:
with open(file_name) as file_object:
contends=file_object.read()
except FileNotFoundError:
msg="Sorry,the file "+file_name+" does not exist."
print(msg)
结果:
Sorry,the file alice.txt does not exist.
1.4 分析文本
title="Alice in Wonderland"
print(title.split()) #split()根据一个字符串创建一个单词列表
file_name='alice.txt'
try:
with open(file_name) as file_object:
contents=file_object.read()
except FileNotFoundError:
msg="Sorry, the file "+file_name+" does not exist."
print(msg)
else:
words=contents.split() #split()根据一个字符串创建一个单词列表,该方法以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中
num_words=len(words)
print("The file "+file_name+" has about "+str(num_words)+" words.")
结果:
The file alice.txt has about 23005 words.
注意:使用文本来自项目:http://www.gutenberg.org/
1.5 使用多个文件
def count_words(filename):
'''计算一个文件大致包含多少个单词'''
try:
with open(file_name) as file_object:
contents=file_object.read()
except FileNotFoundError:
msg="Sorry, the file "+file_name+" does not exist."
print(msg)
else:
words=contents.split() #split()根据一个字符串创建一个单词列表
num_words=len(words)
print("The file "+file_name+" has about "+str(num_words)+" words.")
file_names=['alice.txt','guest.txt','add.txt','reason.txt']
for file_name in file_names:
count_words(file_name)
结果:
The file alice.txt has about 23005 words.
The file guest.txt has about 7 words.
Sorry, the file add.txt does not exist.
The file reason.txt has about 9 words
1.6 失败时一声不吭
def count_words(filename):
'''计算一个文件大致包含多少个单词'''
try:
with open(file_name) as file_object:
contents=file_object.read()
except FileNotFoundError:
# msg="Sorry, the file "+file_name+" does not exist."
# print(msg)
pass #pass让python什么都不要做,同时充当占位符,可能以后会在这里做些什么
else:
words=contents.split() #split()根据一个字符串创建一个单词列表
num_words=len(words)
print("The file "+file_name+" has about "+str(num_words)+" words.")
file_names=['alice.txt','guest.txt','add.txt','reason.txt']
for file_name in file_names:
count_words(file_name)
结果:
The file alice.txt has about 23005 words. #找不到文件时直接跳过
The file guest.txt has about 7 words.
The file reason.txt has about 9 words.
2、存储数据
2.1 使用json.dump()和json.load()
2.1.1 使用json.dump()
import json #导入json模块
numbers=[2,3,5,7,11,19]
filename='numbers.json'
with open(filename,'w') as file_object:
json.dump(numbers,file_object) #json.dump()函数来存储数字列表,两个实参为要存储的数据及存储数据的文件对象
结果:
numbers.json
[2, 3, 5, 7, 11, 19]
2.1.2 使用json.load()
import json #导入json模块
file_name='numbers.json'
with open(file_name) as f_obj:
numbers=json.load(f_obj) #json.load()函数读取内存数据,接受参数为存储数据的文件对象
print(numbers)
结果:
[2, 3, 5, 7, 11, 19, 23]
2.2 保存和读取用户生成的数据
import json
filename='username.json'
try:
with open(filename) as f_obj:
username=json.load(f_obj)
except FileNotFoundError:
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, wangwu!
2.3 重构
import json
def get_stored_username():
filename='username.json'
try:
with open(filename) as f_obj:
username=json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
'''提示用户输入用户名'''
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_username()
print("We'll remember you when you come back, "+username+"!")
greet_user()
根据执行功能分别定义函数,使代码清晰而易于维护。