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则不行。
时间: 2024-12-25 07:33:29