如何从StringIO、BytesIO等中移除字节

4 投票
2 回答
6239 浏览
提问于 2025-04-18 12:13

我想用一个BytesIO对象作为一个连续的缓冲区(这是一个常见的用法)。不过,能不能把那些不再需要的字节从开头去掉呢?

看起来是不行的,因为它只有一个truncate()方法。

['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__getstate__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', 'close', 'closed', 'detach', 'fileno', 'flush', 'getvalue', 'isatty', 'next', 'read', 'read1', 'readable', 'readinto', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

2 个回答

0

我在找一种方法来清空BytesIO的内容。看到martijn-pieters的回答后,我意识到这是不可能的。

不过,我决定提出一个解决方案(重建 BytesIO):

import io 

class BytesIO(io.BytesIO):
    def delete(self):
        self.close()
        super().__init__(b'')


b = BytesIO()
b.write(b'milad')
b.delete()

print(b.getvalue()) # -> b''
7

不可以,因为 BytesIO 是一种在内存中处理的文件对象。

它被当作一串字节来使用,可以进行覆盖或添加内容。不过,就像处理文件一样,从开头删除内容并不高效,因为这需要重新写入后面的所有数据。

你可能应该看看 collections.deque() 类型,这可能更适合你的需求。

撰写回答