Vladimir Gamalian Vladimir Gamalian - 1 year ago 141
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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download