Python之JOSN

簡述

模塊json讓你能夠將簡單的Python數據結構轉出到文件中,並在程序再次運行時加載該文件中的數據。你還可以使用json在Python程序之間分享數據。更重要的是,JSON數據格式並非Python專用,這讓你能夠將以JSON格式存儲的數據與使用其他編程語言的人分享。

使用json.dump()和json.load()

我們來編寫一個存儲一組數字的簡單程序,再編寫一個將這些數字讀取到內存中的程序。

number_writer.py

import json 
numbers = [2,3,5,7,9,11,13]

filename = 'number.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)  

執行結果:

這裏寫圖片描述

注意:數據存儲格式與Python中一樣。

下面編寫一個程序,使用json.load()將這個列表讀取到內存中:

numbers_reader.py

import json 

filename = 'number.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)    
print(numbers)

輸出結果:

這裏寫圖片描述

案例

下面我們編寫一個賓館問候系統,實現歡迎老用戶回來以及問候新用戶

import json

def get_stored_username():  #如果存儲了用戶名,就獲取它
    filename = 'user.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's your name:")
    filename = 'user.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 back, "+username+'!')

greet_user()

輸出結果:

這裏寫圖片描述

再次執行:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章