Vladimir Gamalian Vladimir Gamalian - 9 months ago 73
Python Question

Invert first byte in file

What is the most pythonic way to change first byte of file to its inversion copy?
Now, I use this code:

with open(file_path, 'r+b') as f:
b = bytearray(f.read(1))
b[0] = ~b[0] & 255


Here's an alternative that uses a memory-mapped file:

import mmap

with open(file_path, 'r+b') as f, mmap.mmap(f.fileno(), 1) as mm:
    mm[0] ^= 255