except、json用法

import json


def remember_me():
    file_name = 'User.json'
    try:
        with open(file_name) as r_obj:
            username = json.load(r_obj)
            
    # ①可以用except Error_1 or Error_2;②当json文件存在,内容空白时,会出现json.JSONDecodeError
    except json.JSONDecodeError or FileNotFoundError:
        username = input('Please key in your name:')
        with open(file_name, 'w') as object_1:  # 与这行的object_1一致
            json.dump(username,
                      object_1)  # 像这行,json.dump(contents to write, object_file) 这个object_file一定是和上面的object_1一致的
    else:
        print('We have remembered you,' + username + '!')
    
    with open(file_name) as object_2:  # 同理,json括号中的内容,一定是和 as object_name中的object_name一致。
        contents = json.load(object_2)  #
        print('Nice to see you again,' + contents + '!')


if __name__ == '__main__':
    remember_me()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值