首页 > 代码库 > [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)