我正在尝试确定在我的代码中使用的最佳内部接口(interface),特别是围绕如何处理文件内容。实际上,文件内容只是二进制数据,因此字节足以表示它们。
我将文件存储在不同的远程位置,因此有几个不同的类用于读取和写入。我正在尝试找出用于我的功能的最佳界面。最初我使用的是文件路径,但这是次优的,因为这意味着磁盘总是被使用(这意味着很多笨拙的临时文件)。
代码的多个区域具有相同的要求,并且将直接使用从此接口(interface)返回的任何内容。因此,无论我选择什么抽象,都会涉及到相当多的代码。
使用 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):
我发现使用类文件接口(interface)(BytesIO 等)需要在 seek(0)
等方面增加一些管理开销。这引发了一个问题,例如:
- 在开始之前
寻求
更好,还是在完成之后更好? - 您是
寻找
到开头还是从文件所在的位置开始操作? - 你应该
tell()
保持这个位置吗? - 查看像
shutil.copyfileobj
这样的东西,它不做任何搜索
我发现使用类似文件的接口(interface)的一个优点是它允许在检索数据时传入要写入的 fp。这似乎提供了很大的灵 active 。
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 中设计接口(interface)时,是否有充分的理由更喜欢 BytesIO 而不是仅使用固定字节?
最佳答案
io.BytesIO
对象的好处是它们实现了一个通用的接口(interface)(通常称为“类文件”对象)。 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 )。
关于python - Python 中的内部接口(interface)更喜欢 BytesIO 还是 bytes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28590300/