everyday

Python IO Module - Read & Write

BytesIO provides convenient way of writing and reading into streams. There is also seek function which helps to look ahead in the stream.

It should be noted that all streams should be in bytes rather than strings.

# io_bytesio.py
import io

# writing to buffer
output = io.BytesIO()
output.write('this goes into the buffer....'.encode('utf-8'))
output.write('ÁÇÊ'.encode('utf-8'))

# retrieve the value written
print(output.getvalue())
output.close()

# initialize a read buffer
input = io.BytesIO(b'initial value for read buffer')
print(input.read())
python3 io_bytesio.py 

b'this goes into the buffer....\xc3\x81\xc3\x87\xc3\x8a'

b'initial value for read buffer'

This is part of series of articles from Python Module of the Week

#pymotw

- 1 toast