Listing 09-18: Binary file viewer

##############################################################################
# Python From Scratch
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2024
# Site: https://pythonfromscratch.com
#
# File: listing\chapter 09\09.18 - Binary file viewer.py
# Description: Binary file viewer
##############################################################################

import sys
import itertools


def print_bytes(image, bytes_per_line=16):
    for b in itertools.batched(image, bytes_per_line):
        hex_view = " ".join([f"{v:02x}" for v in b])
        tview = "".join([chr(v) if chr(v).isprintable() else "." for v in b])
        print(f"{hex_view} {" " * 3 * (bytes_per_line - len(b))}{tview}")


if __name__ == "__main__":
    with open(sys.argv[1], "rb") as f:
        image = f.read()
    print_bytes(image)
Click here to download the file