美文网首页python
python(20):文件和异常(2)------异常和存储数据

python(20):文件和异常(2)------异常和存储数据

作者: Z_bioinfo | 来源:发表于2022-04-13 15:29 被阅读0次

    1.异常

    python发生错误时,会创建一个异常对象,如果编写了处理该异常的代码,程序将继续运行,如果没有编写,程序将停止,并显示一个traceback,其中包含异常的报告。

    1.ZeroDivisionError异常
    print(5/0)#这样做会出现异常
    ZeroDivisionError                         Traceback (most recent call last)
    <ipython-input-2-244cf93eeabc> in <module>
          3 #使用try-except代码块处理异常
          4 #####1.处理异常
    ----> 5 print(5/0)
    
    ZeroDivisionError: division by zero
    
    2.使用try-except代码块处理异常
    try:
        print(5/0)
    except ZeroDivisionError: #出现异常后如何做
        print('you can not divide by zero')
    you can not divide by zero
    
    3.使用异常避免崩溃

    当输入5和0时,程序崩溃,运行不出结果

    print('give me two numbers, and i will divide them')
    print("enter 'q' to quit")
    
    while True:
        first_number = input('\nfirst number: ')
        if first_number == 'q':
            break
        second_number = input('\nsecond number: ')
        if second_number == 'q':
            break
        answer = int(first_number)/int(second_number)
        print(answer)
    give me two numbers, and i will divide them
    enter 'q' to quit
    
    first number: 5
    
    second number: 0
    ---------------------------------------------------------------------------
    ZeroDivisionError                         Traceback (most recent call last)
    <ipython-input-1-e2f10f797953> in <module>
         10     if second_number == 'q':
         11         break
    ---> 12     answer = int(first_number)/int(second_number)
         13     print(answer)
    
    ZeroDivisionError: division by zero
    
    4.解决办法
    print('give me two numbers, and i will divide them')
    print("enter 'q' to quit")
    
    while True:
        first_number = input('\nfirst number: ')
        if first_number == 'q':
            break
        second_number = input('\nsecond number: ')
        if second_number == 'q':
            break
        try:
            answer = int(first_number)/int(second_number)
        except ZeroDivisionError: #出现异常后如何做
            print('you can not divide by zero')
        else:#不出现异常时怎么办
            print(answer)
    give me two numbers, and i will divide them
    enter 'q' to quit
    
    first number: 5
    
    second number: 0
    you can not divide by zero
    
    first number: 5
    
    second number: 2
    2.5
    
    5.处理FileNotFoundError异常

    原因:查找的文件可能在其它地方,文件名不正确或这个文件根本不存在

    with open('tmp.txt') as tmp:
        contents = tmp,read()
    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-1-963f3942d4a5> in <module>
          1 #####5.处理FileNotFoundError异常
          2 #原因:查找的文件可能在其它地方,文件名不正确或这个文件根本不存在
    ----> 3 with open('tmp.txt') as tmp:
          4     contents = tmp,read()
    
    FileNotFoundError: [Errno 2] No such file or directory: 'tmp.txt'
    ================================================
    #解决办法
    try:
        with open('tmp.txt') as tmp:
            contents = tmp.read()
    except FileNotFoundError:
        print("对不起,该文件不存在")
    对不起,该文件不存在
    
    6.分析文本

    使用split()函数将文本中包含的单词创建为一个列表

    try:
        with open('tmp.txt') as tmp:
            contents = tmp.read()
    except FileNotFoundError:
        print("对不起,该文件不存在")
    else:
        words = contents.split():
        num_words = len(words)
        print('the file tmp.txt ' +  'has about ' + str(num_words) + 'words')
    
    7.分析多个文件,可使用函数处理
    #先计算一个文件包含多少单词
    def count_words(filename):
        try:
        with open(filename) as tmp:
            contents = tmp.read()
    except FileNotFoundError:
        print("对不起,该文件不存在")
    else:
        words = contents.split():
        num_words = len(words)
        print('the file tmp.txt ' +  'has about ' + str(num_words) + 'words')
    
    filename = 'alice.txt'
    count_words(filename)
    =======================================
    #通过循环统计多个文件包含多少单词
    def count_words(filename):
        --snip--
    
    filenames = ['alice.txt', 'a.txt', 'b.txt', 'c.txt']
    for filename in filenames:
        count_words(filename)
    
    8.希望程序发生异常时一声不吭
    def count_words(filename):
        try:
        with open(filename) as tmp:
            contents = tmp.read()
        except FileNotFoundError:
            pass#使用pass语句处理
        else:
            words = contents.split():
            num_words = len(words)
            print('the file tmp.txt ' +  'has about ' + str(num_words) + 'words')
    
    filename = 'alice.txt'
    count_words(filename)
    

    2.存储数据

    模块json能够将简单的python数据结构存储在文件中,并在程序再次运行时加载该文件,也可以在python程序之间分享数据

    1.json.dump,存储内容,包括两个实参,要存储的数据以及可用于存储数据的文件对象

    import json
    numbers = [1, 2, 3, 4, 5]
    filename = 'numbers.json'
    with open(filename, 'w') as f_obj:
        json.dump(numbers, f_obj)#将数字列表存储到文件json.dump中
    
    image.png

    2. json.load #加载文件

    import json
    filename = 'numbers.json'
    with open(filename) as f_obj:
        numbers = json.load(f_obj)
        
    print(numbers)
    [1, 2, 3, 4, 5]
    

    3.保存和存储用户生成的数据

    对于用户生成的数据,使用json保存很好用,首次运行程序时被提示输入数据,再次运行程序就会记住他

    import json
    username = input('请输入姓名: ')
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print('我们将记住你的选择' + username)
    请输入姓名: 大明
    我们将记住你的选择大明
    ======================================
    ###打开文件时向用户发出问候
    import json
    filename = 'username.json'
    with open(filename) as f_obj:
        username = json.load(f_obj)
        print('欢迎回来 '+ username)
    欢迎回来 大明
    

    5.重构

    代码能够正确运行,但可做进一步改进,将代码划分为一系列完成具体工作的函数,这个过程叫重构

    #假设有一个函数
    import json
    
    def greet_user():
        filename = 'username.json'
        try:
            with open(filename) as f_obj: 
                username = json.load(f_obj)
        except FileNotFoundError:
            username = input('请输入姓名: ')
            with open(filename, 'w') as f_obj:
                json.dump(username, f_obj)
                print('我们将记住你的选择' + username)
        else:
            print('欢迎回来 '+ username)
            
    greet_user()
    欢迎回来 大明
    #重构greet_user(),让它不执行那么多任务,将获取存储用户名的代码移到另一个函数中
    
    import json
    
    def get_stored_username():
        #如果存储了用户名就读取它
        filename = 'username.json'
        try:
            with open(filename) as f_obj: 
                username = json.load(f_obj)
        except FileNotFoundError:
            return None#函数要么返回预期值,要么返回None
        else:
            return username
    def greet_user():
        username = get_stored_username()
        if username:#如果获取了用户名,就打印一条欢迎用户回来的消息,否则提示用户输入用户名
           print('欢迎回来 '+ username)
        else:
            username = input('请输入姓名: ') 
            filename = 'username.json'
            with open(filename, 'w') as f_obj:
                json.dump(username, f_obj)
                print('我们将记住你的选择' + username)
    greet_user()
    或者将greet_user()单独放在一个函数中
    import json
    
    def get_stored_username():
        #如果存储了用户名就读取它
        filename = 'username.json'
        try:
            with open(filename) as f_obj: 
                username = json.load(f_obj)
        except FileNotFoundError:
            return None#函数要么返回预期值,要么返回None
        else:
            return username
    
    def get_new_username():
        username = input('请输入姓名: ') 
        filename = 'username.json'
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)
            print('我们将记住你的选择' + username)
        return username
    
    def greet_user():
        username = get_stored_username()
        if username:#如果获取了用户名,就打印一条欢迎用户回来的消息,否则提示用户输入用户名
           print('欢迎回来 '+ username)
        else:
            username = get_new_username()
            print('我们将记住你的选择' + username)
            
    greet_user()
    

    相关文章

      网友评论

        本文标题:python(20):文件和异常(2)------异常和存储数据

        本文链接:https://www.haomeiwen.com/subject/obkwsrtx.html