Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Copy Files and Rename in Python
Next article icon

Reading binary files in Python

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Reading binary files means reading data that is stored in a binary format, which is not human-readable. Unlike text files, which store data as readable characters, binary files store data as raw bytes. Binary files store data as a sequence of bytes. Each byte can represent a wide range of values, from simple text characters to more complex data structures like images, videos and executable programs.

Different Modes for Binary Files in Python

When working with binary files in Python, there are specific modes we can use to open them:

  • 'rb': Read binary - Opens the file for reading in binary mode.
  • 'wb': Write binary - Opens the file for writing in binary mode.
  • 'ab': Append binary - Opens the file for appending in binary mode.

Opening a Binary File

To read a binary file, you need to use Python’s built-in open() function, but with the mode 'rb', which stands for read binary. The 'rb' mode tells Python that you intend to read the file in binary format, and it will not try to decode the data into a string (as it would with text files).

file = open("file_name", "rb")

After opening the binary file, you can use different methods to read its content.

Using read()

The open() function is used to open files in Python. When dealing with binary files, we need to specify the mode as 'rb' (read binary) and then use read() to read the binary file.

Python
f = open('example.bin', 'rb')  bin = f.read() print(bin)  f.close() 

Output:

b"b'\\x00\\nNotoSanSha\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\r\nx00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00LWFNGWp1\\'"

Explanation: This code opens a binary file (example.bin) in read binary mode ('rb'). It reads the entire content of the file into the variable bin as bytes using the read() method. After reading the content, it prints the binary data. Finally, it closes the file using f.close() to release system resources.

Using readlines()

By using readlines() method we can read all lines in a file. However, in binary mode, it returns a list of lines, each ending with a newline byte (b'\n').

Python
with open('example.bin', 'rb') as f:     lines = f.readlines()     for i in lines:         print(i) 

Output:

b"b'\\x00\\nNotoSanSha\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\r\n"
b'x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00LWFNGWp1\\'

Explanation:

  • The code opens a binary file (example.bin) in read-binary mode ('rb').
  • readlines() reads all lines from the file into a list. Each item in the list is a byte object, representing a line in the binary file.
  • The for loop iterates over each line, printing it as it goes.

Reading Binary File in Chunks

Reading a binary file in chunks is useful when dealing with large files that cannot be read into memory all at once. This uses read(size) method which reads up to size bytes from the file. If the size is not specified, it reads until the end of the file.

Python
size = 1024    with open('example.bin', 'rb') as f:     while True:         chunk = f.read(size)         if not chunk:             break                  print(chunk) 

Output:

b"b'\\x00\\nNotoSanSha\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\r\nx00
\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00LWFNGWp1\\"

Explanation:

  • The file example.bin is opened in read-binary mode ('rb').
  • The code reads the file in chunks of 1024 bytes using f.read(size).
  • The while True loop continues until the file is fully read, breaking when no more data is available (f.read(size) returns an empty chunk). Each chunk is printed to the console.

Related Articles:

  • Python | Convert String to bytes
  • Python Array
  • Read a file line by line in Python
  • Reading and Writing a text file in Python

Next Article
Copy Files and Rename in Python

G

greeshmanalla
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • Python fileinput-library
Practice Tags :
  • python

Similar Reads

  • Reading CSV files in Python
    A CSV (Comma Separated Values) file is a form of plain text document that uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fie
    5 min read
  • Read File As String in Python
    Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
    3 min read
  • Python | Reading .ini Configuration Files
    This article aims to read configuration files written in the common .ini configuration file format. The configparser module can be used to read configuration files. Code #1 : Configuration File abc.ini ; Sample configuration file [installation] library = %(prefix)s/lib include = %(prefix)s/include b
    3 min read
  • Read JSON file using Python
    The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
    4 min read
  • Copy Files and Rename in Python
    Copying and renaming files is a common task in programming, and Python provides several ways to accomplish this efficiently. In this article, we will explore some commonly used methods for copying files and renaming them: using the shutil module's copy() and pathlib module's Path class. Each method
    2 min read
  • How To Read .Data Files In Python?
    Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
    4 min read
  • Copy And Replace Files in Python
    In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, thi
    2 min read
  • Reading Rows from a CSV File in Python
    CSV stands for Comma Separated Values. This file format is a delimited text file that uses a comma as a delimiter to separate the text present in it. Or in other words, CSV files are used to store data in tabular form. As per the name suggested, this file contains the data which is separated by a co
    5 min read
  • Python - Read file from sibling directory
    In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__S
    3 min read
  • Read a file line by line in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Example [GFGTABS] Python # O
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences