15.7. Files Binary

  • Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage

  • It requires conversions between unicode and binary data using a character codec

  • This can become noticeable handling huge amounts of text data like large log files

  • Source: https://docs.python.org/3/library/io.html#id3

15.7.1. Append Binary

  • mode='ab' - append in binary mode

>>> DATA = b'Hello World'
>>>
>>> with open('/tmp/myfile.bin', mode='ab') as file:
...     file.write(DATA)
11

15.7.2. Write Binary

  • mode='wb' - write in binary mode

>>> DATA = b'Hello World'
>>>
>>> with open('/tmp/myfile.bin', mode='wb') as file:
...     file.write(DATA)
11

15.7.3. Read Binary

  • mode='rb' - read in binary mode

>>> with open('/tmp/myfile.bin', mode='rb') as file:
...     data = file.read()
...
>>> result = data.decode()
>>> print(result)
Hello World

15.7.4. Seek

  • Go to the n-th byte in the file

  • Supports negative index (from end of file)

>>> DATA = b'Hello World'
>>>
>>> with open('/tmp/myfile.bin', mode='wb') as file:
...     file.write(DATA)
11
>>> with open('/tmp/myfile.bin', mode='rb') as file:
...     position = file.seek(6)
...     data = file.read(5)
>>>
>>> result = data.decode()
>>> print(result)
World