码迷,mamicode.com
首页 > 编程语言 > 详细

python3 pickle, json

时间:2016-03-26 10:57:49      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

pickle 有dump ,dumps ,load,loads等方法。区别在于dumps不会写入到文件。

技术分享
 1 import pickle
 2 
 3 string = [a, 2341, adsf]
 4 
 5 p_str= pickle.dumps(string)
 6 print(p_str)
 7 l_str = pickle.loads(p_str)
 8 print(l_str)
 9 
10 p_str1 = This is a test!
11 with open(d:/python/pydev/day3/src/p.pkl, wb) as file:
12     pickle.dump(p_str1, file)
13 
14 with open(d:/python/pydev/day3/src/p.pkl, rb ) as file1:  
15     l_file = pickle.load(file1)
16 
17 print(l_file)
pickle

结果如下:

b‘\x80\x03]q\x00(X\x01\x00\x00\x00aq\x01M%\tX\x04\x00\x00\x00adsfq\x02e.‘
[‘a‘, 2341, ‘adsf‘]
This is a test!

 

‘‘‘
The file argument must have a write() method that accepts a single bytes argument.
It can thus be an on-disk file opened for binary writing
‘‘‘

注意:pickle以二进制处理,所以文件打开方式应该加上b, 如‘wb‘.‘rb‘如果仅以w方式打开则会报错,这里可能理解有误,奇怪的是json用wb会报错,而w则正常。

技术分享
 1 import json
 2 
 3 string = [a, 2341, adsf]
 4 
 5 p_str= json.dumps(string)
 6 print(p_str)
 7 l_str = json.loads(p_str)
 8 print(l_str)
 9 
10 p_str1 = This is a test!
11 with open(d:/python/pydev/day3/src/p.pkl, w) as file:
12     json.dump(p_str1, file)
13 
14 with open(d:/python/pydev/day3/src/p.pkl, r ) as file1:  
15     l_file = json.load(file1)
16 
17 print(l_file)
json

运行结果:

["a", 2341, "adsf"]
[‘a‘, 2341, ‘adsf‘]
This is a test!

pickle是python特有的,而json支持语言很多。另外json dump的结果是可以直接读的,pickle则不行。

 

python3 pickle, json

标签:

原文地址:http://www.cnblogs.com/Andy963/p/5322065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!