- 使用 json.dump() 和 json.load()
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
- 保存和读取用户数据
import json
filename = 'username.json'
def remember_user():
username_r = input("What is your name? ")
with open(filename, 'w') as f_obj:
json.dump(username_r, f_obj)
print("We'll remember you when you come back, " + username_r + "!")
def greet_user():
with open(filename) as f_obj:
username_g = json.load(f_obj)
return username_g
try:
username = greet_user()
except FileNotFoundError:
remember_user()
else:
print("Welcome back, " + username + "!")
- 重构
import json
filename = 'username.json'
def get_stored_username():
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? ")
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 + "!")
本文参考自 《Python 编程:从入门到实践》