I would like to modify a file containing a hex dump. There are 33 lines which contain strings like this:
0000000000000000b00b8000c7600795
0001906da451000000008fac0b000000
I would like to put two spaces after every two characters, like this:
00 00 00 00 00 00 00 00 b0 0b 80 00 c7 60 07 95
So far I've made this script that works, but it puts two spaces in each character. I can't see what parameter I can use with .join()
to make it every two characters:
import os
os.rename( 'hex_dump.txt', 'hex_dump.old' )
destination = open( 'hex_dump.txt', "w" )
source = open( 'hex_dump.old', "r" )
for line in source:
if len(line) > 2:
destination.write(" ".join(line))
source.close()
destination.close()
Say you have a file hex_dump.txt
with the following contents:
0000000000000000b00b8000c7600795
0001906da451000000008fac0b000000
You could use str.join
:
#!/usr/bin/python3.9
import os
os.rename('hex_dump.txt', 'hex_dump.old')
with open('hex_dump.txt', 'w') as dest, open('hex_dump.old', 'r') as src:
for line in src:
if len(line) > 2:
dest.write(' '.join(line[i:i + 2] for i in range(0, len(line), 2)))
hex_dump.txt
after running above:
00 00 00 00 00 00 00 00 b0 0b 80 00 c7 60 07 95
00 01 90 6d a4 51 00 00 00 00 8f ac 0b 00 00 00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With