1、使用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)
[2, 3, 5, 7, 11, 13]
2德挣、保存和讀取用戶生成的數(shù)據(jù)
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? jian
We'll remember you when you come back, jian!
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back, " + username + "!")
Welcome back, jian!
import json
# 如果以前存儲(chǔ)了用戶名换吧,就加載它
# 否則管引,就提示用戶輸入用戶名并存儲(chǔ)它
filename = 'username.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 + "!")
Welcome back, jian!