把处理后的文件用open('txt', 'w') 和 print()输出出来 finally

man = []        #创建列表
other = []
try:
    data = open('sketch.txt')

    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()   #去除空白符
            if role == 'Man':
               man.append(line_spoken)      #将man的话添到man[]
               
            elif role == 'Other Man':       
               other.append(line_spoken)        #将other man的话添到列表
           
             

       
        except ValueError:      #异常处理
            pass
    if 'data' in locals():      #调用方法locals()判断‘data’文件是否存在当前环境中
        data.close()
    
except IOError:     #I/O错误处理
    print('The data file is missing!')

#将处理的数据写入man1.txt和other2.txt文档

try:
    man1 = open("man1.txt", "w")        #调用open()方法创建写入文件'w'为写入参数,open()默认为'r'读
    other2 = open("other2.txt", "w")
    
    print(man, file=man1)    #print()
    print(other, file=other2)
    
except IOError:
    print('file  error')

finally:    #确保打开的文件关闭及时try遇到异常也会关掉man1和other2文件防止数据丢失
if 'man1' in locals(): man1.close() if 'other2' in locals(): other2.close()

finally方法过于臃肿

转载于:https://www.cnblogs.com/nester-liz/p/9526231.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值