pathlib – Read file as BytesIO binary stream

We can open a file as binary and load it into a BytesIO binary stream.

This is useful if we don’t want to open a file as just bytes alone, but would rather have the file opened as a file-like object, like a BytesIO object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from io import BytesIO
from pathlib import Path


# Create path object to an existing file
source_path = Path("myfiles", "images", "test.jpg")

# Open the file in read-binary mode using the pathlib Path object.
with source_path.open(mode="rb") as f:

    # Load the bytes data as a binary stream
    original_binary_stream = BytesIO(f.read())

print(type(original_binary_stream))
>> <class '_io.BytesIO'>