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 9101112131415
fromioimportBytesIOfrompathlibimportPath# Create path object to an existing filesource_path=Path("myfiles","images","test.jpg")# Open the file in read-binary mode using the pathlib Path object.withsource_path.open(mode="rb")asf:# Load the bytes data as a binary streamoriginal_binary_stream=BytesIO(f.read())print(type(original_binary_stream))>><class'_io.BytesIO'>