Read Binary File in Python
Read bytes from a binary file and print their length.
BeginnerFile Handling ProgramsExample 10 of 20
read-binary-file.py
1# Program to read a binary file23filename = input("Enter binary filename: ")45try:6 with open(filename, "rb") as f:7 data = f.read()8 print("Read", len(data), "bytes")9except FileNotFoundError:10 print("Binary file not found.")
Output
Enter binary filename: image.png Read 10240 bytes
What's going on
Opening in "rb" mode reads raw bytes rather than decoding text.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.