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()

输出结果:

这里写图片描述

再次执行:

这里写图片描述

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