Python文件与异常--处理错误

Python文件与异常–处理错误

head frist python 第三章个人测试代码如下 :

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 27 16:23:46 2017

@author: einstein_father
"""
#import os
#os.getcwd()
#当前工作目录
man = []
other = []

try:
    #if os.path.exists('sketch.txt')
    #用if会先导入os库,然后使用path.exists确保数据文件存在,之后才去打开文件,占用了空间,应该用try
    data = open('sketch.txt')
    #data.seek(0)回到0下标
    #each_line = 'i tell you, yes or no.'
    #each_line.find()
    #如果没有冒号:会打印-1
    for each_line in data:
        try:
            #if not each_line.find(':') == -1:
            #使用if会先去检查数据是否符合格式要求,降低了效率,应该用try
            (role,line_spoken) = each_line.split(':', 1)
            #删除字符串前面和后面的空白符
            line_spoken = line_spoken.strip()
            if role == 'Man':
                man.append(line_spoken)
            elif role =='Other Man':
                other.append(line_spoken)
            #多重赋值,以:分割
#            print(role, end = '')
#            print(' said: ', end = '')
#            print(line_spoken, end = '')
        except ValueError:
            pass
    data.close()
except  IOError:
    print('data file missing')

try:
    out_1 = open('man.txt', 'w')
    out_2 = open('other.txt', 'a')
    #追加
    print(man, file = out_1)
    print(other, file = out_2)
except IOError:
    print('out file error')
finally:
    #close不要写在try里面
    out_1.close()
    out_2.close()

#s = ["Other Man: Now let's get one thing quite clear: I most definitely told you!"]
#for i in s:
#    (role,line_spoken) = i.split(':', 1)
#    print(role, end = ' said:')
#    print(line_spoken)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值