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)