JSON( Javascript Object )格式

json.dump( )两个实参:1. 要存储的数据 2.可用于存储数据的文件对象

   如 with open(filename, 'w') as f_obj:

      json.dump(numbers, f_obj)

json.load( )加载文件中的信息,1个实参:要读取信息的文件对象

练习:使用json存储和读取用户信息

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 will remember you when you come back, " + username + "!")


greet_user()
posted on 2018-06-29 21:16  浅塘  阅读(411)  评论(0编辑  收藏  举报