Python 中的内部接口更喜欢 BytesIO 还是 bytes?

Prefer BytesIO or bytes for internal interface in Python?

我正在尝试确定在我的代码中使用的最佳内部接口,特别是关于如何处理文件内容。实际上,文件内容只是二进制数据,所以字节足以表示它们。

我将文件存储在不同的远程位置,因此有几个不同的 类 用于读取和写入。我正在尝试找出用于我的功能的最佳界面。最初我使用的是文件路径,但这是次优的,因为这意味着磁盘总是被使用(这意味着很多笨拙的临时文件)。

代码中有几个地方有相同的要求,将直接使用从此接口返回的任何内容。因此,无论我选择什么抽象,都会涉及到相当多的代码。

使用 BytesIO 与字节的各种权衡是什么?

def put_file(location, contents_as_bytes):
def put_file(location, contents_as_fp):
def get_file_contents(location):
def get_file_contents(location, fp):

我发现使用类文件接口(BytesIO 等)在 seek(0) 等方面需要一些管理开销。这引发了一个问题,例如:

我发现使用类似文件的接口的一个优点是它允许在检索数据时传入要写入的 fp。这似乎提供了很大的灵活性。

def get_file_contents(location, write_into=None):
    if not write_into:
        write_into = io.BytesIO()

    # get the contents and put it into write_into

    return write_into

get_file_contents('blah', file_on_disk)
get_file_contents('blah', gzip_file)
get_file_contents('blah', temp_file)
get_file_contents('blah', bytes_io)
new_bytes_io = get_file_contents('blah')
# etc

在 python 中设计接口时,是否有充分的理由更喜欢 BytesIO 而不是仅使用固定字节?

io.BytesIO 对象的好处是它们实现了一个通用接口(通常称为 'file-like' 对象)。 BytesIO 对象有一个内部指针(其位置由 tell() 返回)并且每次调用 read(n) 指针前进 n 字节。例如

import io

buf = io.BytesIO(b'Hello world!')
buf.read(1) # Returns b'H'

buf.tell()  # Returns 1
buf.read(1) # Returns b'e'

buf.tell() # Returns 2

# Set the pointer to 0.
buf.seek(0)
buf.read() # This will return b'H', like the first call.

在您的用例中,bytes 对象和 io.BytesIO 对象都可能不是最佳解决方案。他们会将您文件的完整内容读入内存。

相反,您可以查看 tempfile.TemporaryFile (https://docs.python.org/3/library/tempfile.html)。