python3 pickle, json

Posted 安迪_963

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 pickle, json相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

python3之序列化(pickle&json)

python3--json与pickle数据序列化

Python3学习之路~5.7 Json & pickle 模块

Python3 json &pickle 数据序列化

python3_json&pickle

Python3 从零单排9_json&pickle&shelve