如何在 Python 中将 BytesIO 内容写入文件

为了将 BytesIO 实例的内容写入文件,使用此代码片段:

write_bytesio_to_file.py
with open("out.txt", "wb") as outfile:
    # 将 BytesIO 流复制到输出文件
    outfile.write(myio.getbuffer())

注意 getbuffer() 不会创建 BytesIO 缓冲区中值的副本,因此不会消耗大量内存。

你也可以使用此函数:

write_bytesio_func.py
def write_bytesio_to_file(filename, bytesio):
    """
    将给定 BytesIO 的内容写入文件。
    如果文件尚不存在则创建文件或覆盖文件。
    """
    with open(filename, "wb") as outfile:
        # 将 BytesIO 流复制到输出文件
        outfile.write(bytesio.getbuffer())

完整示例:

bytesio_full_example.py
#!/usr/bin/env python3
from io import BytesIO
import shutil

# 初始化我们的 BytesIO
myio = BytesIO()
myio.write(b"Test 123")

def write_bytesio_to_file(filename, bytesio):
    """
    将给定 BytesIO 的内容写入文件。
    如果文件尚不存在则创建文件或覆盖文件。
    """
    with open(filename, "wb") as outfile:
        # 将 BytesIO 流复制到输出文件
        outfile.write(bytesio.getbuffer())

write_bytesio_to_file("out.txt", myio)

Check out similar posts by category: Python