Why read the entire file to change four bytes at the beginning? Shouldn't this work?
with open("filename.txt", "r+b") as f:
f.write(chr(10) + chr(20) + chr(30) + chr(40))
Even if you need to read these bytes from a file to calculate the new values, you can still:
with open("filename.txt", "r+b") as f:
fourbytes = [ord(b) for b in f.read(4)]
fourbytes[0] = fourbytes[1]
f.seek(0)
f.write("".join(chr(b) for b in fourbytes))
source
share