How to Read Binary File Bytes and Inspect the Header in Python
Read the first bytes of a binary file with pathlib and display them as a hex dump plus an ASCII view to inspect file headers.
Python code
23 linesimport pathlib
def inspect_binary_header(filepath: str, num_bytes: int = 16) -> None:
"""Read the first bytes of a binary file and display them as hex and ASCII."""
path = pathlib.Path(filepath)
data = path.read_bytes()[:num_bytes]
hex_str = ' '.join(f"{byte:02x}" for byte in data)
ascii_str = ''.join(chr(byte) if 32 <= byte <= 126 else '.' for byte in data)
print(f"File: {path.name}")
print(f"Total size: {path.stat().st_size} bytes")
print(f"First {len(data)} bytes:")
print(f" Hex: {hex_str}")
print(f" ASCII: {ascii_str}")
if __name__ == "__main__":
# Create a sample binary file for demonstration
sample_path = pathlib.Path("sample.bin")
sample_path.write_bytes(bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x01, 0x02, 0xFF]))
inspect_binary_header(sample_path)
sample_path.unlink() # Clean up the sample file
Output
File: sample.bin
Total size: 12 bytes
First 12 bytes:
Hex: 89 50 4e 47 0d 0a 1a 0a 00 01 02 ff
ASCII: .PNG.......
How it works
pathlib.Path.read_bytes() returns the entire file as a bytes object in one call, so we slice it with [:num_bytes] to get just the header. The hex string is built with a generator expression that formats each byte as a zero-padded two-digit hex value. The ASCII view uses chr() only for printable bytes (32–126) and a period for anything else, making non-text bytes visible. path.stat().st_size gives the total file size without reading the whole file again. This pattern is a lightweight way to sniff file types or validate formats before parsing the full content.
Common mistakes
- Using `open(filepath, 'rb')` and `.read(16)` without closing the file — `Path.read_bytes()` handles closing automatically.
- Forgetting that byte values are integers 0–255, not characters, when formatting hex.
- Slicing before checking whether the file is shorter than the requested bytes, which can yield fewer bytes than expected (handled here by using `len(data)`).
Variations
- Use `open(filepath, 'rb') as f: data = f.read(16)` for streaming, which reads only the first 16 bytes without loading the entire file.
- Use the `binascii.hexlify` function for a compact hex string: `binascii.hexlify(data).decode()`.
Real-world use cases
- Verify that a downloaded file matches an expected magic number (e.g., PNG header) before processing it as an image.
- Automatically detect file type in a batch upload system by reading the first few bytes instead of trusting the filename extension.
- Troubleshoot corrupt or mislabeled files in ETL pipelines by inspecting the raw header bytes to see the actual format.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.