How to modify a binary state of a file in python? -


i'm desperated now.
no matter how hard tried, searched , made different scripts, still can't modify way need to.
it's simple, want read first byte of file, in binary it's 00 00 00 10, complement 11 11 11 01 , write in it's place, if file 2 bytes example, :

00 00 00 10 #first byte 01 10 10 10  #second byte 

after modification be:

11 11 11 01 #complement of first byte 01 10 10 10  #second byte remains intact 

it appreciated if shed light on problem.

it sounds want read-append mode.

with open('file', 'r+b') file:     data = f.read(1)[0]     data = (~data) % 256     file.seek(0)     file.write(bytes((data,))) 

opening mode r+b. r read, + means enable writing, b means binary, result of reads bytes object instead of string.

f.read(1)[0] reads first byte of file , extracts values resulting bytes object integer (the indexed value of bytes object integer)

~data negation of returned byte. since python doesn't have real byte type, use % 256 wrap result 0-255 range.

file.seek(0) returns start of file next write replaces first byte. seek takes offset in bytes.

lastly write data file. bytes takes sequence of integers in 0-255 range give tuple (data,). alternatively, use integer's to_bytes method , skip wrapping this:

with open('file', 'r+b') file:     data = f.read(1)[0]     data = ~data     file.seek(0)     file.write(data.to_bytes(1, 'little', signed=true)) 

read returns bytes object array of bytes. when access one, returns value @ each index integer. convert array of bytes single integer can use int.from_bytes. arguments bytes object, string 'big' or 'little' indicating endianness, , optional keyword argument signed tells whether interpret bytes signed or not. convert can use .to_bytes method on int object takes 3 arguments: number of bytes convert to, plus endianness , whether or not interpret signed data.

so work more 1 byte @ time, can read different number of bytes.

you can seek byte offset within file @ time before reading or writing. can use file.tell() find out how many bytes in file before trying seek or read.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -