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() #strip()BIF将':'前后的内容去空格
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)