Reputation: 39
Suppose I have a file of string of bytes that looks something as below:
00101000000000011000000000000011001.......
I want to read every 8th bits of the binary file and write it in a new file. How do I do it in python?
Upvotes: 1
Views: 90
Reputation: 3276
endianness = 'big'
with open('from.txt', 'rb') as r:
with open('to.txt', 'wb') as w:
while True:
chars = r.read(8)
if len(chars) == 8:
string = ''.join([str(byte % 2) for byte in chars])
if endianness == 'little':
string = string[::-1]
byte = int(string, 2).to_bytes(1, endianness)
w.write(byte)
else:
break
Upvotes: 1