python3 pickle, json

时间:2022-07-04 12:15:14

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

 import pickle

 string = ['a', 2341, 'adsf']

 p_str= pickle.dumps(string)
print(p_str)
l_str = pickle.loads(p_str)
print(l_str) p_str1 = 'This is a test!'
with open('d:/python/pydev/day3/src/p.pkl', 'wb') as file:
pickle.dump(p_str1, file) with open('d:/python/pydev/day3/src/p.pkl', 'rb' ) as file1:
l_file = pickle.load(file1) 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则正常。

 import json

 string = ['a', 2341, 'adsf']

 p_str= json.dumps(string)
print(p_str)
l_str = json.loads(p_str)
print(l_str) p_str1 = 'This is a test!'
with open('d:/python/pydev/day3/src/p.pkl', 'w') as file:
json.dump(p_str1, file) with open('d:/python/pydev/day3/src/p.pkl', 'r' ) as file1:
l_file = json.load(file1) print(l_file)

json

运行结果:

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

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