首页 > 代码库 > 六.自定义函数(三)
六.自定义函数(三)
1.使用IDLE的异常信息:
try:
data=http://www.mamicode.com/open(‘missing.txt‘)
print(data.readline(),end=‘‘)
"""为异常对象给定一个名,然后作为错误消息的一部分"""
except IOError as err:
"""使用str()BIF要求异常对象表现为一个字符串"""
print(‘File error:‘+str(err))
finally:
"""文件不存在时,数据文件对象并未创建,这样就不可能在数据对象上调用close()方法,尝试调用close()之前先查看data名是否存在"""
if ‘data‘ in locals():
data.close()
2.用with处理文件:优化后的代码最终版
man=[]
other=[]
try:
data=http://www.mamicode.com/open(‘sketch.txt‘)
for each_line in data:
try:
(role,spoken_line)=each_line.split(‘:‘,1)
spoken_line=spoken_line.strip()
if role ==‘Man‘:
man.append(spoken_line)
elif role ==‘Other Man‘:
other.append(spoken_line)
except ValueError:
pass
except IOError as :
print(‘the data file is missing‘)
try:
"""with语句不再需要包含一个finally组来处理文件的关闭"""
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 err:
print(‘File error:‘+str(err))
3.优化输出的数据格式:修改之前的print_lol()函数,让它把数据输出到一个磁盘文件而不是显示在屏幕上(标准输出)
步骤:向print_lol()函数增加第4个参数,用来标识将把数据写入哪个位置,要为这个参数提供一个缺省值sys.stdout
def print_lol(the_list,indent=False,level=0,fn=sys.stdout):
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item,indent,level+1,fn)
else:
if indent:
for tab_stop in range(level):
print("\t",end=‘‘,file=fh)
print(each_item,file=fh)
这时,将之前的代码中的print()改用print_lol(),调用的格式为print_lol(man,fh=man_file)和print_lol(man,fh=other_file)
4.使用pickle标准库“腌制”数据并持久存储:用dump保存,用load恢复
用dump代替print_lol()函数:
import pickle
man=[]
other=[]
try:
data=http://www.mamicode.com/open(‘sketch.txt‘)
for each_line in data:
try:
(role,spoken_line)=each_line.split(‘:‘,1)
spoken_line=spoken_line.strip()
if role ==‘Man‘:
man.append(spoken_line)
elif role ==‘Other Man‘:
other.append(spoken_line)
except ValueError:
pass
except IOError:
print(‘the data file is missing‘)
try:
"""将访问模式改为可写二进制模式"""
with open(‘man_data.txt‘,‘wb‘) as man_file,with open(‘other_data.txt‘,‘wb‘) as other_file
"""将两个nester.print_lol()调用替换为pickle.dump()调用"""
pickle.dump(man,man_file)
pickle.dump(other,other_file)
except IOError as err:
print(‘File error:‘+str(err))
except pickle.PickleError as perr:
print(‘Pickling error:‘+str(err))
5.使用pickle和nester来解除腌制的数据:创建一个空列表来存放解除腌制的数据:
new_man=[]
try:
with open(‘man_data.txt‘,‘rb‘) as man_file:
new_man=pickle.load(man_file)
except IOError as err:
print(‘File erro:‘+str(err))
except pickle.PickleError as perr:
print(‘Pickling error:‘+str(err))
nester.print_lol(new_man)
六.自定义函数(三)