用with来处理文件:
由于处理文件时候try/catch/finally模式相当常用,所以Python提供了一个语句来抽象出相关的一些细节。
try:
data=open('its.txt',"w")
print("it's...",file=data)
except IOError as err:
print('File error: '+str(err))
finally:
if 'data' in locals():
data.close()
try:
with open('its.txt',"w") as data:
print("it's...",file=data)
except IOError as err:
print('File error: '+str(err))
pickle保存加载Python数据对象:
import pickle
with open('mydata.pickle','wb') as mysavsdata:
pickle.dump([1,2,'three'],mysavsdata)
with open('mydata.pickle','rb') as myrestoredata:
a_list=pickle.load(myrestoredata)
print(a_list)
如果出问题了,pickle模块会产生一个PickleError类型的异常。
import pickle
try:
with open('man_data.txt','wb') as man_file,open('other_data.txt','wb') as other_file:
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 err: '+str(perr))