Python3 pickle模块教程

Python
# -*- coding: utf-8 -*- __author__ = 'songhao' import <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/pickle" title="View all posts in pickle" target="_blank">pickle</a></span> shoplistfile = 'shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = open(shoplistfile, 'wb') #以二进制的方式进行写入 <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/pickle" title="View all posts in pickle" target="_blank">pickle</a></span>.dump(shoplist, f) # dump the object to a file 倒入一个文件,存入 f.close() del shoplist # remove the shoplist # Read back from the storage f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # 读入文件 print(storedlist) dump: 写入 load: 读取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding: utf-8 -*-
__author__ = 'songhao'
import pickle
 
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
 
shoplist = [ 'apple' , 'mango' , 'carrot' ]
 
# Write to the file
 
f = open ( shoplistfile , 'wb' ) #以二进制的方式进行写入
 
 
pickle . dump ( shoplist , f )    # dump the object to a file 倒入一个文件,存入
f . close ( )
 
del shoplist    # remove the shoplist
 
# Read back from the storage
f = open ( shoplistfile , 'rb' )
storedlist = pickle . load ( f ) # 读入文件
print ( storedlist )
 
dump : 写入
load : 读取

对于序列化最普遍的做法就是使用 pickle 模块。为了将一个对象保存到一个文件中,可以这样做:

Python
import pickle data = ... # Some Python object f = open('somefile', 'wb') pickle.dump(data, f) 为了将一个对象转储为一个字符串,可以使用 pickle.dumps() : s = pickle.dumps(data) 为了从字节流中恢复一个对象,使用 picle.load() 或 pickle.loads() 函数。比如: # Restore from a file f = open('somefile', 'rb') data = pickle.load(f) # Restore from a string 将一个字符串恢复成对象 data = pickle.loads(s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import pickle
 
data = . . . # Some Python object
f = open ( 'somefile' , 'wb' )
pickle . dump ( data , f )
为了将一个对象转储为一个字符串,可以使用 pickle . dumps ( ) :
 
s = pickle . dumps ( data )
为了从字节流中恢复一个对象,使用 picle . load ( ) 或 pickle . loads ( ) 函数。比如:
 
# Restore from a file
f = open ( 'somefile' , 'rb' )
data = pickle . load ( f )
 
# Restore from a string 将一个字符串恢复成对象
data = pickle . loads ( s )



  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值