Vladimir Gamalyan
Vladimir Gamalyan

Reputation: 255

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)

Upvotes: 1

Views: 137

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114841

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

Upvotes: 2

Related Questions