• 四.自定义函数(二)


    1.错误处理

    data=open('sketch.txt')

    for each_line in data:

      try:

        (role,spoken_line)=each_line.split(':',1)

        print(role,end='')

        print('  said:',end='')

        print(spoken_line,end='')

      except:

        pass

    data.close()

    2.如果是文件被删除的情况,上面的代码处理不了,对其进行改进:

    try:

      data=open('sketch.txt')

      try:

        for each_line in data:

          (role,spoken_line)=each_line.split(':',1)

          print(role,end='')

          print(' said:',end='')

          print(spoken_line,end='')

      except:

          pass

      data.close()

    except:

      print('the data file is missing')

    3.上面的异常处理太过一般化,可以特定指定异常,输出异常信息,优化代码如下:

    try:

      data=open('sketch.txt')

      for each_line in data:

        try:

          (role,spoken_line)=each_line.split(':',1)

          print(role,end='')

          print(' said:',end='')

          pirnt(spoken_line,end='')

        except ValueError:

          pass

        data.close()

    except IOError:

      print('the data file is missing')

  • 相关阅读:
    Android 开发转型前端准备知识
    atom写文档技巧
    gerrit升级到16.04之后连接不到服务器
    adb shell am pm
    ArrayList和LinkedList的区别
    Android源码编译
    Android动态加载代码技术
    File 与 FileStream 文件运用
    物体在一定范围自有碰撞
    扫描二维码加载网页图片
  • 原文地址:https://www.cnblogs.com/chenshaoping/p/7216832.html
Copyright © 2020-2023  润新知