Python中异常和JSON读写数据

异常可以防止出现一些不友好的信息返回给用户,有助于提升程序的可用性,在java中通过try ... catch ... finally来处理异常,在Python中通过try ... except ... else来处理异常

一、以ZeroDivisionError为例,处理分母为0的除法异常

def division(numerator,denominator):
    result=numerator/denominator
    return result
        
ret1=division(1,5)
print(ret1)

ret2=division(1,0)
print(ret2)

1/5执行正常,输出0.2,但1/0,分母为0,抛出Traceback,该信息看起来非常不友好,try .. except可以获取这些异常信息,并且允许转换为用户可读性较好的提示。

def division(numerator,denominator):
    try:
        result=numerator/denominator
        return result
    except ZeroDivisionError:
        return "denominator can not be zero"
    except BaseException:
        return "pls check if the numerator and denominator is number."
    else:
        return "unknow error"
           
ret1=division(1,5)
print(ret1)

ret2=division(1,0)
print(ret2)

1/5正常计算,1/0提示“denominator can not be zero”,这个信息就比较友好,可读性强。

一开始,我在这里犯了一个错误,在try块中没有返回result,程序输出了如下结果

1/5的时候,try块没有发生异常,所以接下来的两个except都不会进入,故就进入到了else处,返回了unknow error,所以我们在使用异常时,一定要记得返回

如果在换一种方式,是否也可以正常返回结果

def division(numerator,denominator):
    try:
        result=numerator/denominator
    except ZeroDivisionError:
        result = "denominator can not be zero"
    except BaseException:
        result = "pls check if the numerator and denominator is number."
    else:
        result = "unknow error"
    return result
        
ret1=division(1,5)
print(ret1)

ret2=division(1,0)
print(ret2)

结果也和预期不一致,所以在使用异常处理时,如果方法中有返回值,则一定要记得在try块中也返回结果,如果try块中执行正常,异常处理在try执行结束后结束,不再向下执行。

二、JSON 读写数据

JSON(JavaScript Object Notation),最开始只有JavaScript语言使用,但由于其优良的数据格式形式,逐渐被很多编程语言引用,如java中也是用到了JSON,并且有很多对应的类库处理JSON数据。Python中对JSON数据的读取和保存可以使用json.load()和json.dump()方法.

json.dump方法接收两个参数,第一个参数为要保存的json数据,第二个数据为打开的文件对象,使用时注意顺序。

json.load方法接收一个文件对象作为参数

另外json还存在很多其他的方法,比如json.dumps将python数据类型进行json格式编码,可以简单理解为将列表/字典转换为json字符串,json.loads与json.dumps刚好相反,将json字符串转换为列表/字典

如当用户登录后,让其输入名称,然后根据json文件中是否存在该用户给出不同的提示

1、JSON写入

import json
filename="myjson.json"
with open(filename,'w') as wr:
    json.dump([1,2,3,4],wr)

2、JSON读取

import json
filename="myjson.json"
with open(filename) as re:
    ls=json.load(re)


print(ls)

json读取时,文件必须存在,且不能为空,且内容格式要符合json规范

文件内容为空以及不符合json格式规范,都会出现如下异常

3、使用JSON读取实现一个简单的需求

用户首次登陆,提示欢迎信息,并将其登录信息记录到以SON格式保存到文件中,当该用户下次登录后,将显示欢迎回来,并且提示其上次登录时间。输入quit退出程序

import json
import os
import time
import sys
import traceback
def login():
    json_file="./username.json"
    while(True):
        name=input("pls input your name: ")
        if "quit" == name:
            sys.exit(0)
        curr_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        user_dict_list=[]
        if os.path.exists(json_file):
            with open(json_file) as jf:
                try:
                    # 文件内容为空,或者文件内容,或者不符合json格式,所以此处添加异常处理
                    user_dict_list=json.load(jf)
                    isExist=False
                    for ele in user_dict_list:
                        username=ele.get("username")
                        if username == name:
                            isExist=True
                            ele["lastLoginTime"]=curr_time
                            print ("welcome back: %s, last login : %s"%(name,curr_time))
                            break;
                
                    if isExist == False:
                        # 文件存在,且内容格式正确,但不存在当前用户
                        first_login(user_dict_list,name,curr_time)
                except Exception:
                    # 打印出异常信息,便于调测程序,正式使用事可以去掉,或者打印在后台,不给用户看到
                    traceback.print_exc()
                    #文件内容为空,或者文件内容格式不符合JSON要求
                    first_login(user_dict_list,name,curr_time)
        else:
            # 文件不存在
            first_login(user_dict_list,name,curr_time)
        # 将用户信息写入/重新写入到文件中
        with open(json_file,'w') as jf:
            json.dump(user_dict_list,jf)
        
''' 将用户第一次登陆信息存放到集合中 '''
def first_login(user_dict_list,name,curr_time):
    my_dict={"username":name,"lastLoginTime":curr_time}
    user_dict_list.append(my_dict)
    print ("welcome: %s, have a nice day."%(name))
    
login()

输入zhangsan和lisi,由于都是第一次登陆,所以打印出欢迎信息,再次数次zhangsan,由于其已经登录过,故其名称和上次登录时间已经被记录下来,再次登录,打印出欢迎回来,及上次登录时间,输入quit退出程序。由于开发环境已经设置了UTF-8编码,输入中文也是支持的

原文地址:https://www.cnblogs.com/qq931399960/p/11124480.html