学习的主要是从文件读取数据、异常处理基本语法
本节课学习如何使用Python向文本文件中写入数据、异常处理的深入补充

'''''将上课demo中的谈话内容(conversations)按角色(role)的不同,分别存入两个文本文件中'''
man = [] #分别定义两个list 用来存储两个role的conversations
other = []
try:
data = open('sketch.txt')
try:
for each_line in data:
(role, line_spoken) = each_line.split(':', 1)
line_spoken = line_spoken.strip()
if role == 'man': #通过判断role来确定要存入的list
man.append(line_spoken)
else:
other.append(line_spoken)
except ValueError:
pass
data.close() #别忘了完成文件操作关闭数据文件对象
except IOError:
print('The file is missing!')
try:
man_file = open('man_data.txt', 'w') #数据文件对象中的文件参数如果不存在,并且相应目录有相应权限,open()会自动创建文件
other_file = open('other_data.txt', 'w') # 'w'为文件数据对象的'写'模式
print(man, file = man_file) #print()函数中的file参数为写入的文件名
print(other, file = other_file)
man_file.close() #别忘了完成文件操作关闭数据文件对象
other_file.close()
except IOError:
print('File Error!')

2、改进上面代码中的异常处理逻辑和代码: 

上面代码中的异常处理方式依旧是不完善的,想想看,如果在man_file.close()语句之前,代码发生了错误,那么数据文件对象是不会被关闭掉的。

改进代码:

man = []
other = []
try:
data = open('sketch.txt')
try:
for each_line in data:
(role, line_spoken) = each_line.split(':', 1)
line_spoken = line_spoken.strip()
if role == 'man':
man.append(line_spoken)
else:
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError as ioerr: #将IOError异常对象赋予ioerr变量
print('File Error :' + str(ioerr)) #将ioerr转换为字符串类型
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 as ioerr:
print('File Error: ' + str(ioerr))
finally: #无论try代码块或者except代码块中的语句是否被执行,finally代码块中的语句
if 'man_file' in locals(): #判断数据文件对象是否存在,loclas() BIF返回作用域中所有变量的字典
man_file.close()
if 'man_file' in locals():
man_file.close()

3、Python中 文件处理的语法糖:

利用with语句,可以将文件处理的代码简化,无需考虑关闭文件,裁剪掉文件异常处理语句中的finally语句。
作用一:简化语法,减少工作量。
作用二:通过逻辑抽象,减少码农脑细胞死亡速度和出错概率。

对以上代码第二段之改进:

try:
with open('man_data.txt', 'w') as man_file:
print(man, file = man_file)
with open('other_data.txt', 'w') as other_file:
print(other, file = other_file)
except IOError as ioerr:
print('File Error: ' + str(ioerr))

OR

try:
with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
print(man, file = man_file)
print(other, file = other_file)
except IOError as ioerr:
print('File Error: ' + str(ioerr))

python中三种处理文件输出的方式:

#读取一个文件中的数据,将其分成两部分内容,并保存在两个文件

import os
os.getcwd()
os.chdir('E:\HeadFirstPython\chapter4') #切换到原文件存放路径
import neater
import pickle
man=[]
other=[]
try:
data = open('sketch.txt') #尝试打开已有的文件sketch.txt
for each_line in data: #用for和in读取data对象中的每个数据
try:
(role,line_spoken)=each_line.split(':',1) #split()BIF将sketch中的数据按照':'为分隔符进行分开,且只分为两部分
line_spoken=line_spoken.strip()  <span style="font-family: Arial, Helvetica, sans-serif;">#strip()BIF将':'前后的内容去空格</span>
if role=='Man':
man.append(line_spoken) #如果分开的两部分前面是man,就将其后面的内容放到man这个列表中
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print("The data file is missing")
#第一种实现方式,使用try/except/finally,这种机制中,不论成功失败都会执行finally,所以文件都会正常关闭
'''''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()'''
#第二种实现方式,使用try/except/with,不用finally,with可以代替finally中执行的步骤,且更简洁
'''''try:
with open('man_data2.txt','w') as man_file2:
neater.print_lol(man,fh=man_file2)
with open('other_data2.txt','w') as other_file2:
neater.print_lol(other,fh=other_file2)
except IOError as err:
print('File Error'+str(err))'''
#第三种实现方式,使用pickle,数据腌制的方法,这种方法调用pickle标准库,腌制得到的文件会持久存储,可以任何一个时期读入到另外一个程序
try:
with open('man_data3.txt','wb') as man_file,open('other_data3.txt','wb') as other_file:
pickle.dump(man,man_file)
pickle.dump(other,other_file)
except IOError as err:
print('File Error:'+str(err))

#neater.py 定义print_lol

import sys
def print_lol(the_list,indent=False,level=0,fh=sys.stdout):
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item,indent,level+1,fh)
else:
if indent:
for tap_stop in range(level):
print("\t",end='',file=fh)
print(each_item,file=fh)