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!

  • 相关阅读:
    swift3.0 coreData的使用-日记本demo
    Objective-C plist文件与KVC 的使用
    swift3.0 CoreGraphics绘图-实现画板
    Objective-C 使用核心动画CAAnimation实现动画
    Objectiv-C UIKit基础 NSLayoutConstraint的使用(VFL实现)
    Objectiv-c
    C语言基础
    C语言基础
    swift 3.0 基础练习 面向对象 类的扩展
    myIsEqualToString
  • 原文地址:https://www.cnblogs.com/pingh/p/3439149.html
Copyright © 2011-2022 走看看