首页 > 代码库 > [Head First Python]4. pickle.dump pickle.load
[Head First Python]4. pickle.dump pickle.load
sketch.py
1 #--*-- coding:utf-8 --*-- 2 import pickle 3 import nester 4 man = [] 5 other = [] 6 try: 7 data = http://www.mamicode.com/open ("datafile.txt") 8 9 for each_line in data:10 try: 11 (role, line_spoken) = each_line.split(":", 1)12 line_spoken = line_spoken.strip()13 if role == ‘Man‘:14 man.append(line_spoken)15 elif role == ‘Other Man‘:16 other.append(line_spoken) 17 18 except ValueError:19 pass20 21 data.close()22 except IOError:23 print(‘this data file is missing!‘)24 25 try:26 with open(‘man.out‘, ‘wb‘) as man_out, open(‘other.out‘,‘wb‘) as other_out:27 pickle.dump(man, man_out) #二进制存储数据到文件28 pickle.dump(other, other_out)29 30 except pickle.PickleError as perr:31 print(‘pickle error‘ + str(perr))32 33 new_man = []34 try:35 with open(‘man.out‘, ‘rb‘) as man_file:36 new_man = pickle.load(man_file) #二进制文件数据读取到list37 except IOError as err:38 print(‘file error‘ + str(err))39 except pickle.PickleError as perr:40 print(‘pickle err‘ + str(perr))41 42 nester.print_lol(new_man)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。