0

I just learned to write python language, how do I want to do the wrap-line output?

I've done googling and the results aren't there, or don't know the keywords

The code is like this :

import binascii

filename = 'file.pdf'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))

The result will be like this, just single line : 255044462d312e340a25c3a4c3bcc3b6c39f0a322

But I want to make it like this, for example wrapped after 10 characters : 0x25, 0x50, 0x44, ...

Can anyone help me? Thanks!

  • 4
    https://docs.python.org/3.7/library/textwrap.html may be of interest to you. Or do you want [How do you split a list into evenly sized chunks?](https://stackoverflow.com/q/312443/953482)? – Kevin Apr 30 '19 at 12:46
  • Do you want bytes with a decimal value less than 16 *displayed* with a zero padding like `0x0f` or like `0xf`? – wwii Apr 30 '19 at 13:18

3 Answers3

1

You can use textwrap module for wrapping x characters.

This is the code that use textwrap.

import binascii
import textwrap

filename = 'file.pdf'
with open(filename, 'rb') as f:
    content = f.read()
temp = binascii.hexlify(content)
temp_hex = []
# convert bytes to hexadecimal value
for t in temp:
    temp_hex.append(hex(t))
# join the hexadecimal value using "," and wrap with maximum 10 characters each rows
print(textwrap.fill(",".join(temp_hex), 10))
calmira
  • 39
  • 7
0

Write a generator that splits the string into equal-sized chunks, and use it to split into chunks of 20, then into smaller chunks of length 2:

def split_string(s, chunk_length):
    for i in range(0, len(s), chunk_length):
        yield s[i:i+chunk_length]

hex = binascii.hexlify(content)
for line in split_string(hex, 20):  # divide into chunks of length 20
    print(*split_string(line, 2), sep=", ")    # then into chunks of length 2
Stuart
  • 9,597
  • 1
  • 21
  • 30
0

First write a custom_hexlify function which outputs the desired format by using hex.

text = b'foo bar'

def custom_hexlify(data):
    return ', '.join([hex(c) for c in data])

print(custom_hexlify(text)) # 0x66, 0x6f, 0x6f, 0x20, 0x62, 0x61, 0x72

To wrap the text, you can then use textwrap.wrap.

def print_wrapped_line(*args, **kwargs):
    for line in textwrap.wrap(*args, **kwargs):
        print(line)

print_wrapped_line(custom_hexlify(text), 20)

Output

0x66, 0x6f, 0x6f,
0x20, 0x62, 0x61,
0x72
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73