【问题标题】:Convert bytes into BufferedReader in python [duplicate]在python中将字节转换为BufferedReader [重复]
【发布时间】:2018-04-22 06:37:23
【问题描述】:

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

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'>

但我想要这些类似文件的功能,而不必将字节保存到文件中。换句话说,我想将这些字节包装到缓冲读取器中,这样我就可以对其应用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'

如何将字节写入和读取到对象之类的文件中,而不将其保存到本地磁盘中?

【问题讨论】:

  • import io; file_like = io.BytesIO(sample_bytes)

标签: python arrays file-io io buffer


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2017-12-25
    • 2018-12-17
    • 2021-04-24
    • 2018-06-11
    • 2023-04-02
    • 1970-01-01
    • 2021-05-11
    • 2012-06-02
    相关资源
    最近更新 更多