您的当前位置:首页正文

Python 读写 Json 列表操作练习

来源:华佗小知识
import json

def get_stored_name():
    '''获取 json 文件中的对象'''
    try:
        with open("nameCollect.json", "r") as file_obj:
            name_lsit = json.load(file_obj)
    except FileNotFoundError:
        name_lsit = None
    file_obj.close()
    return name_lsit

def get_new_name():
    '''获取 json 文件中已有的列表,若文件不存在或文件为空,则创建一个空列表'''
    try:
        with open("nameCollect.json", "r") as file_obj:
            name_list = json.load(file_obj)    
    except FileNotFoundError:
        name_list = []
    if name_list is None:
        name_list = []
    '''新输入一个字符串并追加到列表末尾写入 json 文件中'''
    while True:
        username = input("Please input a name(enter \"q\" to exit):  ")
        if username != "q":
            name_list.append(username)
        else:
            break        
    with open("nameCollect.json", "w") as file_obj:
        json.dump(name_list, file_obj)
    file_obj.close()
    return name_list

def say_hi():
    '''向用户询问是执行读取操作还是执行写入操作'''
    while True:
        flg = input("Enter \"1\" to write names into the file, enter \"2\" to say \"Hi\": ")
        if flg == "1":  # 根据用户提示,向文件中写入数据
            get_new_name()
        elif flg == "2":    # 根据用户提示,从文件中读取字符串列表
            name_list = get_stored_name()
            if not name_list:
                name_list = get_new_name()  # 如果文件为空,提示用户向文件中写入数据
            break
        else:
            print("Sorry, you must input 1 or 2.")
    '''若文件为空,告知用户;若文件中列表不为空,则将元素 依次打印出来'''
    if name_list:
        for name in name_list:
            print("Hi, " + name + "!")
    else:
        print("Oh, you didn't input anything here.")
    
say_hi()

欢迎讨论。