《深入浅出Python》4 持久存储

本文探讨了Python中数据的保存方法,包括使用文件保存数据的两种方式:文本模式和二进制模式,并介绍了pickle模块如何实现数据的序列化与反序列化。此外,文章还讨论了集合数据类型的特点及数据规范化的重要性。

程序生成数据

man = []
other = []
try:
	data = open('sketch.txt')
	
	for each_line in data:
		try:
			(role,line_spoken)=each_line.split(':')
			line_spoken = line_spoken.strip()
			if role == 'Man':
				man.append(line_spoken)
			elif role == 'Other Man':
				other.append(line_spoken)
		except ValueError:
			pass
	data.close()
except IOError:
	print('The data file is missing!')
print(man)
print(other)

生成的数据进行保存(前半部分相同)
方法一:

try:
        man_file = open('man_data.txt','w') #man_file为数据文件,man_data.txt为数据文件名,w为要使用的访问模式    
        other_file = open('other_data.txt','w')

        print(man,file = man_file)#print()里第一个参数文要写入的内容,man_file为要写入的数据文件名称
        print(other,file = other_file)

        man_file.close()#完成工作时一点要记得关闭文件,以确保所有数据都写至磁盘,这称为刷新输出
        other_file.close()
except IOError:
        print('File Error')
finally:
        if 'man_file' in locals():
                man_file.close()
        if 'other_file' in locals():
                other_file.close()

方法二:

try:
    with open('man_file.txt','w') as man_file:
        print(man,file = man_file)
    
    with open('other_file.txt','w') as other_file:
        print(other,file = other_file)
        
except IOError as err:
    print('File Error' + str(err))
pickle – "腌制"数据

pickle:python剔红了一个标准库,它可以保存和加载几乎任何Python数据对象,包括列表。
一旦把数据“腌制”到一个文件,它将会持久存储,可以在以后某个时期读入到另外一个程序。也可以将“腌制”数据存储在磁盘上,放在数据库中。

用dump保存,用load恢复

tips:必须以而禁止访问模式打开dump()保存的数据和load()恢复的数据

import pickle #导入pickle模块

with open('mydata.pickle','wb') as mysavedata:# “b”告诉Python要以二进制模式打开数据文件
    pickle.dump([1,2,'three'],mysavedara) # 保存数据使用“dump()”

with open('mydata.pickle','rb') as mysavedata:
    a_list = pickle.load(mydavedata) #使用“load()”从文件恢复数据,将恢复好的数据赋值给一个标识符
print(a_list)

dump

import pickle
man = []
other = []
try:
	data = open('sketch.txt')
	
	for each_line in data:
		try:
			(role,line_spoken)=each_line.split(':')
			line_spoken = line_spoken.strip()
			if role == 'Man':
				man.append(line_spoken)
			elif role == 'Other Man':
				other.append(line_spoken)
		except ValueError:
			pass
	data.close()
except IOError:
	print('The data file is missing!')
try:
    with open('man_file.txt','wb') as man_file:
        pickle.dump(man,man_file)
    
    with open('other_file.txt','wb') as other_file:
        pickle.dump(other,file = other_file)
        
except IOError as err:
    print('File Error' + str(err))	

load

import liebiaoxianshi as lie
import pickle

new_man = []
new_other = []

try:
        try:
                with open('man_file.txt','rb') as man_data:
                        new_man = pickle.load(man_data)
                with open('other_file.txt','rb') as other_data:
                        new_other = pickle.load(other_data)
        except IOError as err:
                print('File error:'+str(err))
except pickle.PickleError as perr:
	print('Picking error:'+str(perr))
lie.print_lol(new_man)	
错误描述

因为看文件夹中已经有man_file.txt文件,所以直接执行了dump 的程序,之后报错,数据怎么序列化进去很重要
在这里插入图片描述

在这里插入图片描述

第四章
教练给了4个人的秒数记录,让你进行排序
james:
2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22
julie:
2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21
mikey:
2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38
sarah:
2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55
但是你发现,这里面的数,进行排序的时候根本不是你想要的结果,你发排序之后,短横线>点号>冒号
所以你要将数字都进行规范化之后再进行排序操作
于是写了一个如下的函数,来进行符号的转换:

def sanitize(time_string)

if '-' in time_string:
    splitter = '-'
elif ':' in time_string:
    splitter = ':'
else:
    return (time_string)
(mins,secs) = time_string.split(splitter)
return(mins+'.'+secs)
要点
  1. 集合中的数据是无需的,而且不允许重复
  2. 工厂函数:set(),创建一个空集合
  3. with语句利用了一种名为上下文管理协议的python技术
  4. wb 二进制模式写入,默认编码utf-8,
    rb 二进制模式读取 二进制模式读取
  5. strip():从字符串中去除不想要的空白符
  6. print():BIF的file参数控制将数据发送/保存到哪里
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值