在 python 中将大文件 (500MB+) 编码为 base64

Encoding large file(500MB+) to base64 in python

我正在尝试对一个大约 500 MB 的大型 exe 文件进行 base64 编码,但在执行此操作时出现此错误:

F:\python\waft>python count.py
Traceback (most recent call last):
  File "count.py", line 10, in <module>
    encodedZip = base64.b64encode(f.read())
  File "C:\Users\rohan-pc\AppData\Local\Programs\Python\Python38-32\lib\base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
MemoryError

这是我编写的用于从 exe 生成 base64 的代码。我做了一些研究,了解到存在一些内存限制,但有没有其他方法可以编码更大的文件..?

with open("test.exe", "rb") as f:
    encodedZip = base64.b64encode(f.read())

我建议分块读取、编码和写入,最好使用像 base64io.

这样的库
from base64io import Base64IO

with open("test.exe", "rb") as f:
    encodedZip = Base64IO(f)

您可以通过 base64io 库使用 Base64 编码的流媒体接口。这会将它分成块,然后在 base64 操作之前。这将是管理大文件编码内存的更好方法。

pip install base64io

经过一些研究后,我得到了以下代码有效的答案:

fr = open("test.exe", 'rb')

i = 1
while True:
    piece = fr.read(75232000)
    if not piece:
        break
    fw = open(str(i), 'wb')
    fw.write(base64.b64encode(piece))
    fw.close()
    i += 1
fr.close()