周六笔记:用json存python的数据

231 阅读1分钟

会自动生成json类型的文件

import json
def greet_user():
    '''问候用户,并指出其名字'''
    file_name = 'username.json'
    try:
        with open(file_name) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        username  = input("what is your name?")
        with open(file_name,'w') as f_obj:
            json.dump(username,f_obj)
            print("we'll remeber you when you come back,"+username+"!")
    else:
       print("Welcome back,"+username+"!")
#调用函数
greet_user()

运行结果图片如下:

参考资料:OLIVER的博客