在 Python 中将 io.BytesIO 内容复制到文件

问题:

在 Python 中,你有一个包含某些数据的 io.BytesIO 实例。你想将该数据复制到文件(或另一个类文件对象)。

解决方案

使用此函数:

copy_filelike.py
def copy_filelike_to_filelike(src, dst, bufsize=16384):
    while True:
        buf = src.read(bufsize)
        if not buf:
            break
        dst.write(buf)

用法示例:

copy_bytesio_example.py
import io

myBytesIO = io.BytesIO(b"test123")

with open("myfile.txt", "wb") as outfile:
    copy_filelike_to_filelike(myBytesIO, outfile)
# myfile.txt 现在包含 "test123"(没有尾随换行符)

Check out similar posts by category: Python