python pickle

# Author:Alex
# Date:2017.0605
# Version:3.6.0
man = []
other = []
#打开note文件,循环内容,并判断,加入到man and other中
import pickle

try:
data = open('note.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)
# print (role, end='')
# print ('said: ', end='')
# print (line_spoken, end='')
except ValueError:
pass
data.close()
except IOError:
print ('The data file is missing')

# try:
# man_file = open('man_data.txt','w+')
# other_file = open('other_data.txt','w+')
#
# print_lol(man,fh=man_file)
# print_lol(other,fh=other_file)
#
# except IOError as err:
# print ('File error:' + str(err))
# finally:
# if 'man_file' in locals():
# man_file.close()
# if 'other_file' in locals():
# other_file.close()
#代替try+except+finally,使用with,将note内容分开,导入两个文件中,man_data and other_data中
try:
with open('man_data.txt',"wb") as man_file, open('other_data.txt',"wb") as other_file:
# print(man, file=man_file)
# print(other, file=other_file)
# cycle.print_lol(man, fh=man_file)
# cycle.print_lol(other, fh=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 error:' + str(perr))



posted @ 2017-06-05 15:10  Alex_Footprint  阅读(203)  评论(0编辑  收藏  举报