• 五.将数据保存到文件


    1.将打印出来到台词保存到文件中,需要如下步骤:

      1)创建一个空列表,名为man

      2)创建一个空列表,名为other

      3)增加一行代码,删除spoken_line不必要到空白符

      4)给出条件和代码,根据role的值将spoken_line添加到适当到列表中

      5)在屏幕输出各个列表(man和other)

    man=[]

    other=[]

    try:

      data=open('sketch.txt')

      for each_line in data:

        try:

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

          spoken_line=spoken_line.strip()

        if role =='Man':

          man.append(spoken_line)

        elif role =='Other Man':

          other.append(spoken_line)

        except ValueError:

          pass

    except IOError:

      print('the data file is missing')

    可以输出两个新建的列表看一下输出的数据:

    print(man)

    print(other)

        

    2.修改上述代码,将数据保存到磁盘文件中

    man=[]

    other=[]

    try:

      data=open('sketch.txt')

      for each_line in data:

        try:

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

          spoken_line=spoken_line.strip()

        if role =='Man':

          man.append(spoken_line)

        elif role =='Other Man':

          other.append(spoken_line)

        except ValueError:

          pass

    except IOError:

      print('the data file is missing')

    try:

    """在这里以写到形式打开两个数据文件"""

      man_file=open('man_data.txt','w')

      other_file=open('other_data.txt','w')

    """使用print()函数将指定到列表保存到打开到磁盘文件"""

      print(man,file=man_file)

      print(other,file=other_file)

      man_file.close()

      other_file.close()

    except IOError:
      print('File error')

    3.代码优化:上述代码中如果第二个print()调用导致一个IOError,则文件没有被正常关闭,数据可能被破坏,可以用finally扩展try

    man=[]

    other=[]

    try:

      data=open('sketch.txt')

      for each_line in data:

        try:

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

          spoken_line=spoken_line.strip()

        if role =='Man':

          man.append(spoken_line)

        elif role =='Other Man':

          other.append(spoken_line)

        except ValueError:

          pass

    except IOError:

      print('the data file is missing')

    try:

      man_file=open('man_data.txt','w')

      other_file=open('other_data.txt','w')

      print(man,file=man_file)

      print(other,file=other_file)

    except IOError:
      print('File error')

    finally:

      man_file.close()

      other_file.close()

  • 相关阅读:
    【BZOJ-4592】脑洞治疗仪 线段树
    【BZOJ-1369】Gem 树形DP
    【BZOJ-3696】化合物 树形DP + 母函数(什么鬼)
    【BZOJ-2435】道路修建 (树形DP?)DFS
    【BZOJ-4590】自动刷题机 二分 + 判定
    【BZOJ-4591】超能粒子炮·改 数论 + 组合数 + Lucas定理
    【BZOJ-1492】货币兑换Cash DP + 斜率优化 + CDQ分治
    【BZOJ-1324】Exca王者之剑 最小割
    【BZOJ-1017】魔兽地图DotR 树形DP + 背包
    【BZOJ-1131】Sta 树形DP
  • 原文地址:https://www.cnblogs.com/chenshaoping/p/7218044.html
Copyright © 2020-2023  润新知