在Python代码中使用Pickle模块dump一个对象,报错:
>>> with open(path, 'wb') as f:
>>> pickle.dump(self, f)
Traceback (most recent call last):
File "" , line 1, in <module>
OSError: [Errno 22] Invalid argument
相关环境参数:
出现该问题的原因是Pickle的对象太大,超过了2G,在OSX系统中无法直接dump,需要借助bytearray进行文件写入,如下所示:
import pickle
import os.path
file_path = "pkl.pkl"
n_bytes = 2**31
max_bytes = 2**31 - 1
data = bytearray(n_bytes)
## write
bytes_out = pickle.dumps(data)
with open(file_path, 'wb') as f_out:
for idx in range(0, len(bytes_out), max_bytes):
f_out.write(bytes_out[idx:idx+max_bytes])
https://stackoverflow.com/questions/31468117/python-3-can-pickle-handle-byte-objects-larger-than-4gb
https://bugs.python.org/issue24658
https://docs.python.org/3/library/pickle.html
以上就是本文的全部内容,如果您喜欢这篇文章,欢迎将它分享给朋友们。
感谢您的阅读,祝您生活愉快!
作者:小美哥
2019-01-12