• 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!

  • 相关阅读:
    Select2插件ajax方式加载数据并刷新页面数据回显
    转 proguard 混淆工具的用法 (适用于初学者参考)
    转 【Android】- Android与html5交互操作
    转 android开发笔记之handler+Runnable的一个巧妙应用
    转 Android 多线程:手把手教你使用AsyncTask
    转 android design library提供的TabLayout的用法
    转 Android Lifecycle、ViewModel和LiveData
    转 onSaveInstanceState()和onRestoreInstanceState()使用详解
    转 MessageDigest来实现数据加密
    转 GSON
  • 原文地址:https://www.cnblogs.com/pingh/p/3439149.html
Copyright © 2020-2023  润新知