2017-11-09 10 views
0

私はbytearrayを持っていて、バッファリングされた読者に変換したい。これを行う方法は、バイトをファイルに書き込んで再度読み取ることです。BytesearをPythonでBufferedReaderに変換する

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' 

どのように書くと、オブジェクトなどのファイルにバイトを読み込むを取得していますか?あなたが探しているすべては、メモリ内のファイルのようなオブジェクトである場合

+1

'輸入IOを見ていることでしょう。 file_like = io.BytesIO(sample_bytes) ' –

答えて

1

、私は

from io import BytesIO 
file_like = BytesIO(b'this is a sample bytearray') 
print(file_like.read()) 
関連する問題