python第十章 文件和异常
圆周率中包含你的生日吗
filename=‘pi_million_digits.txt’
with open(filename) as file_project:
lines=file_project.readlines()
pi_string=’’
for line in lines:
pi_string+=line.strip()
birthday=input("Enter your birthday,in the form mmddyy: ")
if birthday in pi_string:
print(“Your birthday appears in the first million digits of pi!”)
else:
print(“Your birthday does not appear in the first million digits of pi.”)
Enter your birthday,in the form mmddyy: 880214
Your birthday appears in the first million digits of pi!
使用多个文件
def count_words(filname):
try:
with open(filname) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
# msg=“Sorry,the file “+filname+” does not exist.”
# print(msg)
pass
# pass 什么都不做直接继续往后运行
else:
words=contents.split()
num_words=len(words)
print(“The file “+filname+” has about “+str(num_words)+” words.”)
filename=“alice.txt”
count_words(filename)
filenames=[‘alice.txt’,‘siddharthaxxx.txt’,‘moby_dict.txt’,‘little_women.txt’]
for filename in filenames:
count_words(filename)
The file alice.txt has about 29461 words.
Sorry,the file siddharthaxxx.txt does not exist.(如果用pass不会出现这句打印)
The file moby_dict.txt has about 215136 words.
The file little_women.txt has about 189079 words.
数据存储
json.dump()存储数字列表
import json
numbers=[2,3,5,7,11,13]
filename=‘numbers.json’
with open(filename,‘w’) as f_obj:
json.dump(numbers,f_obj)
json.dump()接受两个实参:要存储的数据以及用于存储数据的文件对象
import json
使用json.load()将列表读取到内存中,打印
filename=‘numbers.json’
with open(filename) as f_obj:
numbers=json.load(f_obj)
print(numbers)
[2, 3, 5, 7, 11, 13]
保存和读取用户的数据
import json
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+”!”)
What is your name? Yangjie
We’ll remember you when you come back, Yangjie!
import json
filename=‘username.json’
with open(filename) as f_obj:
username=json.load(f_obj)
print(“Welcome back, “+username+”!”)
Welcome back, yangjie!
合并以上两个模块为一个程序
import json
filename=‘username3.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+”!”)
重构
import json
重构1 准备
def greet_user():
问候用户,并指出其名字
filename='username.json'
username=''
try:
with open(filename) as f_obj:
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+"!")
greet_user()
import json
重构2 开始“变形”
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 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()
import json
重构3 再次优化
函数1:只负责获取存储中的用户名
def get_stored_username():
“”“如果存储了用户名,就获取它”""
filename=‘username4.json’
try:
with open(filename) as f_obj:
username=json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
函数2:只负责获取并存储新的用户名
def get_new_username():
username = input("What is your name? ")
filename = ‘username4.json’
with open(filename, ‘w’) as f_obj:
json.dump(username, f_obj)
return username
函数3:调用获取存储用户名函数,打招呼
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()