Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python put space every two characters [duplicate]

Tags:

python

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()
like image 537
Rescor Avatar asked Sep 12 '25 21:09

Rescor


1 Answers

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
like image 104
Sash Sinha Avatar answered Sep 14 '25 11:09

Sash Sinha