zoukankan      html  css  js  c++  java
  • Head First Python之3文件与异常

    文件基本操作

    Python从文本读取数据时,一次会到达一个数据行。

     sketch.txt文件

    Man: Is this the right room for an argument?
    Other Man: I've told you once.
    Man: No you haven't!
    Other Man: Yes I have.
    Man: When?
    Other Man: Just now.
    Man: No you didn't!
    Other Man: Yes I did!
    Man: You didn't!
    Other Man: I'm telling you, I did!
    Man: You did not!
    Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
    Man: Ah! (taking out his wallet and paying) Just the five minutes.
    Other Man: Just the five minutes. Thank you.
    Other Man: Anyway, I did.
    Man: You most certainly did not!
    Other Man: Now let's get one thing quite clear: I most definitely told you!
    Man: Oh no you didn't!
    Other Man: Oh yes I did!
    Man: Oh no you didn't!
    Other Man: Oh yes I did!
    Man: Oh look, this isn't an argument!
    (pause)
    Other Man: Yes it is!
    Man: No it isn't!
    (pause)
    Man: It's just contradiction!
    Other Man: No it isn't!
    Man: It IS!
    Other Man: It is NOT!
    Man: You just contradicted me!
    Other Man: No I didn't!
    Man: You DID!
    Other Man: No no no!
    Man: You did just then!
    Other Man: Nonsense!
    Man: (exasperated) Oh, this is futile!!
    (pause)
    Other Man: No it isn't!
    Man: Yes it is!
    

     需求:读取文件,将上面的对话都加上said

    代码如下:

    # coding:utf-8
    import os
    
    # 查看当前工作目录
    print(os.getcwd())
    # 切换为包含数据文件的文件夹
    os.chdir('../../HeadFirstPython/chapter03_except')
    # 再次查看当前工作目录
    print(os.getcwd())
    
    # 打开文本
    data = open('sketch.txt')
    # 获取一个数据行,打印
    print(data.readline(), end='')
    # 再次获取一个数据行,打印
    print(data.readline(), end='')
    
    # 回到文件原始位置
    data.seek(0)
    # data.tell() # 等价
    for each_line in data:
        # 当每一行都存在冒号时,执行if中的操作
        if not each_line.find(':') == -1:
            # 遇到冒号就切割字符串,返回一个字符串列表,赋至一个目变量元组,则称为多重赋值
            # 由于一行字符串中可能有多个: 所以我们需要在使用split方法maxsplit参数
            (role, line_spoken) = each_line.split(":", 1)
            print(role, end='')
            print(' said:', end='')
            print(line_spoken, end='')
    
    # 关闭文件
    data.close()
    

    但是这段代码过于脆弱,但文件格式发生变化或者其他异常情况,还是出问题,这时需要用到异常机制。

     处理异常

    try/except机制

    # coding:utf-8
    
    # 如果文件不存在,异常处理
    try:
        data = open('sketch.txt')
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(":", 1)
                print(role, end='')
                print(' said:', end='')
                print(line_spoken, end='')
            except:
                # 如果出现异常,pass,继续执行代码
                pass
        data.close()
    # 想要捕捉特性的异常,需要制定错误类型
    except IOError:
        print("the data file is missing!")
    # 其他所有的异常
    except:
        print("the data file is broken!")
    

      

    其他:

    判断文件是否存在:

    os.path.exists('sketch.txt')
  • 相关阅读:
    mysql之drop、truncate和delete的区别
    mysql之表结构,表空间,段,区,页,MVCC(待整理)
    mysql之子查询、视图、事务及pymysql等
    mysql之单表查询、多表查询
    解决跨域问题!
    项目--2
    项目--1
    后端接口书写
    VUE-组件
    VUE基本写法
  • 原文地址:https://www.cnblogs.com/lingzeng86/p/6790784.html
Copyright © 2011-2022 走看看