入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜

根据视频自己练习

入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜_第1张图片Pickling – python的对象转化为二进制存放
unpickling – 二进制转化为对象

入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜_第2张图片

import pickle
my_list = [3.1415926,1024,'风魔小次郎',['鱼跃此时海']]
file_pickle = open('my_pickled.pkl','wb')
pickle.dump(my_list,file_pickle)
file_pickle.close()

pickle_file = open('my_pickled.pkl','rb')
my_list2 = pickle.load(pickle_file)
print(my_list2)

上面就是 pickle的基本用法 , 用在这么简单的列表上面是没有意义的 , 但是如果程序里面需要引用一个大的列表,用pickle就很方便了 , 具体可以看天气查询这个例子 ,去掉程序体中的城市列表,如下图:
入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜_第3张图片

课后练习

入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜_第4张图片入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜_第5张图片入门学习-Python-小甲鱼学习资料-Day031-永久存储:腌制一缸美味的泡菜_第6张图片

import pickle
def write_files(boy,girl,count):
    file_name_boy = 'boy_' + str(count) + '.txt'
    file_name_girl = 'girl_' + str(count) + '.txt'
    boy_file = open('d:/' + file_name_boy, 'wb')
    girl_file = open('d:/' + file_name_girl, 'wb')

    pickle.dump(boy,boy_file)
    pickle.dump(girl,girl_file)

    boy_file.close()
    girl_file.close()

def  splite_file(filename):
    f = open(filename)
    boy = []
    girl = []
    count = 1

    for each_line  in f:
        if each_line[:6] !='======':
            #  字符串操作
            (role,line_spoken)=each_line.split(":",1)
            if  role=='小甲鱼':
                boy.append(line_spoken)
            if  role=='小客服':
                girl.append(line_spoken)
        else:
            write_files(boy,girl,count)

            boy = []
            girl = []
            count += 1
    write_files(boy, girl, count)
    f.close()

splite_file('record.txt')

程序已调试 , 运行正常 !

你可能感兴趣的:(Python)