Vladimir Gamalian Vladimir Gamalian - 4 months ago 18
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
f.seek(0)
f.write(b)

Answer

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