在 python 中将字节转换为 BufferedReader

Convert bytes into BufferedReader in python

我有一个字节数组,想转换成缓冲 reader。一种方法是将字节写入文件并再次读取它们。

sample_bytes = bytes('this is a sample bytearray','utf-8')
with open(path,'wb') as f:
    f.write(sample_bytes)
with open(path,'rb') as f:
    extracted_bytes = f.read()
print(type(f))

输出:

<class '_io.BufferedReader'>

但我想要这些类似文件的功能,而不必将字节保存到文件中。换句话说,我想将这些字节包装到缓冲的 reader 中,这样我就可以在其上应用 read() 方法而不必保存到本地磁盘。我尝试了下面的代码

from io import BufferedReader
sample_bytes=bytes('this is a sample bytearray','utf-8')
file_like = BufferedReader(sample_bytes)
print(file_like.read())

但我收到属性错误

AttributeError: 'bytes' object has no attribute 'readable'

如何在不将其保存到本地磁盘的情况下将字节写入和读取对象之类的文件?

如果您要查找的只是内存中的文件类对象,我会查看

from io import BytesIO
file_like = BytesIO(b'this is a sample bytearray')
print(file_like.read())