import json #引入一个名为json的函数,一般用的文件存储
def get_stored_username():
filename='username.json' # 将要读取的文件名称存储在变量filename中
try:
with open(filename) as f: # 以读写的方式打开文件filename,并把这种功能赋值给 f
username=json.load(f) #把 f 的信息读取出来赋值给username
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username=input('what is your name:')
filename='usernmae.json'
with open(filename,'w') as f:
json.dump(username,f) #把 username 的值存储到 f 中
return username
def greet_username():
username=get_stored_username() #获取文件里是否有名称存在
if username:
print('welcome to home %s '%username)
else:
username=get_new_username()
print('welcome to china')
greet_username()
实例: 用户的幸运数字
import json
def input_number():
like_number=input('what is your number:')
filename='like_number.json'
with open(filename,'w') as f:
json.dump(like_number,f)
print('welcome to python %s'%like_number)
def like_new_number():
like_number=get_like_number()
if like_number==None:
input_number()
else:
username=input('what is your name %s ?(yes or no)\n'%like_number)
if username=='yes':
print('%s welcome to home'%like_number)
else:
input_number()
def get_like_number():
try:
filename = 'like_number.json'
with open(filename) as f:
like_number=json.load(f)
except FileNotFoundError:
return None
else:
return like_number
like_new_number()
filename='akl.txt'
with open(filename) as f:
for line in f: line = f.read() #直接读取
print(line) 按行打印,打印的时候空一行 print(line)
print(line.rstrip()) 消除空行
# 逐行读取