python第十章 文件和异常

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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰少2020

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值