第四章刚开始,提出要把sktch.txt 中Man和Othe Man的台词分别储存在两个不同的list里。
刚开始的代码为:
man = [] other = [] try : data = open('sketch.txt') for each_line in data: 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) except ValueError: pass except IOError: print 'the txt is missing' print man print other
其中值得一提的是两个异常的处理。外层的异常是指如果sketch文件不存在时,抛出来的异常为‘the txt is missing’.内层的异常是针对split方法调用时如果没有value值,时执行pass,即忽略不计。
而后,需要把man 和other的分别存储在不同的txt里。这里的代码如下:
man = [] other = [] try : data = open('sketch.txt') for each_line in data: 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) except ValueError: pass except IOError: print('the txt is missing') try: man_part = open('man_part.txt','w') other_part =open('other_part.txt','w') print(man,file = man_part) print(other,file = other_part) man_part.close() other_part.close() except IOError: print('file error')
说明:
自此由于书上是按照 Python3 介绍的,写入文件的方法和Python2不兼容,所以为了方便,我Python的版本也自动改为了3.3.
书上紧接着介绍了finally 格式。
finally是配合try/except使用的,即是无论执行其中哪一种代码,则finally都会执行。
结合此例,则是关闭文件适合执行finally.如下:
finally: man_part.close() other.part.close()
之后又提到了如何显示错误信息。用的标识符是err.
试验一下:
我写了一个Missingtxt.py
try: man_part = open('man_part.txt') man_part.close() except IOError as err: print('file error:' +str(err))
with的使用
with的使用可以取代finally。
例如上述的例子可以改写为:
try: with open('man_part.txt','w') as man_part: print(man,file = man_part) with open('other_part.txt','w') as other_part: print(other,file = other_part) except IOError: print('file error')
Pickle:
pickle是持久储存的作用,是python专有的格式。断电后仍不消失。
import pickle with open('mydata.pickle','wb') as mysavedata: pickle.dump([1,2,'data'], mysavedata) with open('mydata.pickle','rb') as mystoredata: alist = pickle.load(mystoredata) print(alist)
由此改写上述的程序:
import pickle man = [] other = [] try : data = open('sketch.txt') for each_line in data: 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) except ValueError: pass except IOError: print('the txt is missing') try: try: with open('man_part.txt','wb') as man_part: pickle.dump(man,man_part) with open('other_part.txt','wb') as other_part: pickle.dump(other,other_part) except PickleError as perr: print('pickling error'+ str(perr)) except IOError as err: print('file error'+ str(err))