新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python如何用json模塊存儲數(shù)據(jù)

存儲數(shù)據(jù)
很多程序都要求用戶輸入某種信息,程序把用戶提供的信息存儲在列表和字典等數(shù)據(jù)結(jié)構(gòu)中。用戶關(guān)閉程序時,就要保存提供的信息,一種簡單的方式就是使用模塊JSON來存儲數(shù)據(jù)。
模塊json能將簡單的python數(shù)據(jù)結(jié)構(gòu)存儲到文件中,并在程序再次運轉(zhuǎn)時加載該文件中的數(shù)據(jù)。還可以使用json在python程序之間分享數(shù)據(jù),與使用其他編程語言的人分享。
1. 使用json.dump( )和json.load( )
import json numbers = [2, 3, 5, 7, 11, 13] filename = 'number.json' with open(filename, 'w') as f_ojb: # 以寫入模式打開文件 json.dump(numbers, f_ojb) # 使用函數(shù)json.dump()將列表存儲到文件中 with open(filename) as f_ojb: nums = json.load(f_ojb) # 使用函數(shù)json.load()將這個列表讀取到內(nèi)存中 print(nums) # 打印讀取到內(nèi)存中的列表,比較是否與存入的列表相同
運行結(jié)果:
[2, 3, 5, 7, 11, 13]
相關(guān)推薦:《Python視頻教程》
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) # 存儲用戶名與username.json文件中
print("We'll remember you when you come back, " + username + "!")
# 向名字被存儲的用戶發(fā)出問候
with open(filename) as f_obj:
un = json.load(f_obj)
print("\nWelcome back, " + un + "!")
運行結(jié)果:
What is your name? ela We'll remember you when you come back, ela! Welcome back, ela!
優(yōu)化上述代碼:
import json
# 存儲用戶的名字
username = input('What is your name? ')
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj) # 存儲用戶名與username.json文件中
print("We'll remember you when you come back, " + username + "!")
# 向名字被存儲的用戶發(fā)出問候
with open(filename) as f_obj:
un = json.load(f_obj)
print("\nWelcome back, " + un + "!")
運行結(jié)果:
What is your name? ela We'll remember you when you come back, ela! Welcome back, ela!
優(yōu)化上述代碼:
import json
# 若存儲了用戶名就加載;否則提示用戶輸入并存儲
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("\nWelcome back, " + username + "!")
運行結(jié)果:
Welcome back, ela!
3. 重構(gòu)
代碼可以運行,但也可以做進(jìn)一步改進(jìn)——將代碼劃分成一些列完成具體工作的函數(shù):這個過程稱為重構(gòu)。
目的:讓代碼更清晰、易于理解、易擴(kuò)展。
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'll remember you when you come back, " + username + "!")
greet_user() 分享名稱:創(chuàng)新互聯(lián)Python教程:Python如何用json模塊存儲數(shù)據(jù)
文章網(wǎng)址:http://m.fisionsoft.com.cn/article/ccoepdp.html


咨詢
建站咨詢
