五.将数据保存到文件

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()

原文地址:https://www.cnblogs.com/chenshaoping/p/7218044.html