zoukankan      html  css  js  c++  java
  • python学习二(文件与异常)

    Python中使用open BIF与文件交互,与for语句结合使用,一次读取一行

    读取文件sketch.txt,文件内容如下:

    Man: Ah! (taking out his wallet and paying) Just the five minutes.
    Other Man: Just the five minutes. Thank you.
    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 look, this isn't an argument!
    (pause)
    Other Man: Yes it is!
    Man: No it isn't!

    上文中说话人与所说的内容用:隔开。要求程序处理,在说话人的后面加上said,例如

    Man said What's your name?

    Other Man said My name is Bruce。

    注意上文中的第3、7行,第3行中有两个:号,第7行没有:号

    代码1

    data = open('sketch.txt')
    
    for each_line in data:
        (role, line_spoken) = each_line.split(':', 1)
        print(role, end='')
        print(' said: ', end='')
        print(line_spoken, end='')
    
    data.close()

    split(':',1)表示数据只会根据遇到的第1个':'号分成两个部分,这样就消除了上文中第3行额外':'号的影响。

    打印结果如下:红色部分为打印的ValueError异常,因为第7行没有':'号

    Man said: Ah! (taking out his wallet and paying) Just the five minutes.
    Other Man said: Just the five minutes. Thank you.
    Other Man said: Now let's get one thing quite clear: I most definitely told you!
    Man said: Oh no you didn't!
    Other Man said: Oh yes I did!
    Man said: Oh look, this isn't an argument!
    Traceback (most recent call last):
    File "E:workspacePythonTestchapter3page81.py", line 4, in <module>
    (role, line_spoken) = each_line.split(':', 1)
    ValueError: need more than 1 value to unpack

    改写代码,处理异常

    try:
        data = open('sketch.txt')
    
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':')
                print(role, end='')
                print(' said ', end='')
                print(line_spoken, end='')
            except ValueError:
                pass
    
        data.close()
    except IOError:
        print('The datafile is missing!')

    pass表示捕获异常后不做任务处理,正确打印结果如下

    Man said Ah! (taking out his wallet and paying) Just the five minutes.
    Other Man said Just the five minutes. Thank you.
    Man said Oh no you didn't!
    Other Man said Oh yes I did!
    Man said Oh look, this isn't an argument!
    Other Man said Yes it is!
    Man said No it isn't!

  • 相关阅读:
    为什么需要Docker?
    一分钟学会《模板方法模式》
    2018再见|2019你好
    三分钟学会《门面模式》
    策略模式原来这么简单!
    外行人都能看得懂的机器学习,错过了血亏!
    我是如何将博客转成PDF的
    面试前必须知道的MySQL命令【explain】
    count(*)、count(1)和count(列名)的区别
    Linux shell去除字符串中所有空格
  • 原文地址:https://www.cnblogs.com/pingh/p/3439149.html
Copyright © 2011-2022 走看看