Table of Contents
Read binary file
Example
Output
Write to binary file
Home Backend Development Python Tutorial How to read (or write) binary data in Python?

How to read (or write) binary data in Python?

Sep 03, 2023 am 08:57 AM
io bytes Reading (reading) binary data: file Write (write) binary data: file

To read or write binary files, first you need to understand the different file modes for binary files in Python -

model describe
rb Open a file in read-only binary format. The file pointer is at the beginning of the file. This is the default mode.
rb Open a file in binary format for reading and writing. The file pointer is placed at the beginning of the file.
wb Open files written in binary format only. Overwrites the file if it exists. If the file does not exist, a new file is created for writing.
wb Open a file in binary format for writing and reading. If the file exists, the existing file is overwritten. If the file does not exist, a new file is created for reading and writing.
ab Open a file for appending in binary format. If the file exists, the file pointer is at the end of the file. That is, the file is in append mode. If the file does not exist, a new file is created for writing.
ab Open file for appending and reading in binary format. If the file exists, the file pointer is at the end of the file. The file is opened in append mode. If the file does not exist, a new file is created for reading and writing.

Read binary file

Suppose we have a binary file. We can read it using read() method. First, we will open the binary file using the rb mode of the open() method. We have the following source files in the D: drive -

How to read (or write) binary data in Python?

Example

Let’s see the complete code

# Open a binary file
f = open('D:\PythonLogo.png', 'rb')

# Read lines
data = f.read()

# Display the data
print(data)
Copy after login

Output

The binary file is unreadable and the content cannot be recognized. Actual output is greater. Below we show only part of it.

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x04\xb0\x00\x00\x04\xb0\x08\x06\x00\x00\x00
\xeb!\xb3\xcf\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00
cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00u0\x00\x00\xea`\x0
0\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x
93\x00\x00\x00\x07tIME\x07\xe1\x08\n\x07\x16\x07\xc9\xb2\xff\xd3\x00\x00\x80\x00IDATx\xda\
xec\x9dw\xbc]e\x95\xf7\x7f\xcf>\xe7\xa6\x91@\xe8\xc5\x02\xa2\x88\x14q0B\x12\xc0\x99\x00!\x
88(\x02\x9a\x8c\x85"\xea\x80b\xc5\x02\xa1\xf8z\xa78\x8aJ\x13EeF\x1d\xdb\x94\x80@\x08\xea\x
a0\x8c\xe0\x0c\x98\x10`\x94\x92\xd0D@,#\x88\xd4\x90r\xef\xd9\xeb\xfd#\x01\x02i\xe7\x9e\xb3
\xcb\xf3\xac\xfd\xfd~>\xef;
.
.
.
\xcdn\xd2d\xb1Q\xdf\xfa\xe9\x8d|\x8f\x14\x00\x00\x00\xb4\t\x02\x0b\x00\x00\x00\xe0Q\x98\xa
9\xd0\xd5\xc7\x1c$Izp\xee>\x9a\xd8\xfa\x98\x1d\xffdr\x7f\x153\x8f\xfa\xf8\xa3\xcdQJ\x07\xec\x
e5\xc8\xf5X\x95\x96\x1eu\n\xdb\xac\xa4-
{\xf9{\xdbe\xf6\xc0#\xfe\xa7\t\xdd\xaf\xed\x9a\xd9\xd1\xf5\xe4\x83\xdawf\xc7w>m\xdb\xbc5-
X\xff
\xb3\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd02\xff?\xca\x9f\x86X\x17m\x83=\
x00\x00\x00%tEXtdate:create\x002017-08-
10T07:22:07+00:00u\xea\xe6c\x00\x00\x00%tEXtdate:modify\x002017-08-
10T07:22:07+00:00\x04\xb7^\xdf\x00\x00\x00\x00IEND\xaeB`\x82'
Copy after login

Write to binary file

The

wb mode of the open() method is used to open the file in writing format.

Note - The binary file is not readable and the content cannot be recognized

Let's take a look at the complete example. Here, the file will be stored in E drive with the name

Example

MyDemoBinary.bin -

# Open a file in binary format for writing
f = open("E:\MyDemoBinary.bin","wb")

# Elements to be added to the binary file
a = [100, 200, 300]

# Convert the integer elements to a bytearray
myArr = bytearray(a)

# The byte representation ius now written to the file
f.write(myArr)
f.close()
Copy after login

Output

After running the file, the file will be visible in the set path, that is, the E drive -

How to read (or write) binary data in Python?

The above is the detailed content of How to read (or write) binary data in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve 'undefined: io.ReadAll' error in golang? How to solve 'undefined: io.ReadAll' error in golang? Jun 25, 2023 am 10:01 AM

During the development process using Golang, we often encounter some errors. One of them is "undefined:io.ReadAll", this error is mostly caused by using outdated methods. This article will explain how to resolve this error. First, let's look at why this error occurs. Before golang1.15, there was no ReadAll method in the io package. When we use this method, the compiler will prompt "undefined:io.Re

HWID V 2.2 manual activation methods and tutorials HWID V 2.2 manual activation methods and tutorials Oct 20, 2023 pm 07:17 PM

This is for users who want to perform manual activation. If you need help with a tool for you to do this, then check here. We can divide the manual activation process into two parts. 1- From the ready-made batch file make sure the internet is enabled. Open Windows Powershell as administrator and enter the following to list the commands in the order they are given. Enter the key, (replace with the key from the list above) Use the following command &lt;key&gt;slmgr/ipk&lt;key&gt; Download the universal ticket from here and extract the downloaded file. Now enter the following code in Powershell (Get-ItemProper

How to solve 'undefined: bytes.Split' error in golang? How to solve 'undefined: bytes.Split' error in golang? Jun 25, 2023 pm 02:02 PM

In the Go language, the bytes package is a package for manipulating byte types, and it contains many useful methods, such as the Split() method. However, when using the Split() method, you may encounter an "undefined: bytes.Split" error. This error is usually caused by incompatible Go versions or lack of necessary dependent libraries. This article will introduce some methods to solve this error. Method 1: Upgrade the Go version as follows

What does linux io mean? What does linux io mean? Mar 24, 2023 am 09:43 AM

Linux io refers to a file operation; in Linux, a file is a series of binary streams, so during the exchange of information, we all perform data sending and receiving operations on these streams. These operations are referred to as I/O operations; because Linux uses a virtual memory mechanism, so the kernel must be requested through system calls to complete IO operations.

Practical combat: hard disk io read and write test on Linux Practical combat: hard disk io read and write test on Linux Feb 19, 2024 pm 03:40 PM

Concept fio, also known as FlexibleIOTester, is an application written by JensAxboe. Jens is the maintainer of blockIOsubsystem in LinuxKernel. FIO is a tool used to test network file system and disk performance. It is often used to verify machine models and compare file system performance. It automatically sends fio commands to a list of cluster machines and collects IOPS for small files and throughput data for large files. rw=[mode]rwmixwrite=30 In mixed read and write mode, writing accounts for 30% moderead sequential read write sequential write readwrite sequential mixed read and write randwrite random write r

How to solve 'undefined: io.TeeReader' error in golang? How to solve 'undefined: io.TeeReader' error in golang? Jun 25, 2023 am 09:51 AM

When developing with golang, we often encounter various problems and error messages. One of the common problems is the "undefined:io.TeeReader" error. This error usually occurs when the program is compiled, and sometimes it can be frustrating. This article will introduce how to solve this problem so that you can smoothly carry out golang development work. First, let's look at what exactly this error means. when we are using

Use the io/ioutil.WriteFile function to write a string to a file and set file permissions and indentation format Use the io/ioutil.WriteFile function to write a string to a file and set file permissions and indentation format Jul 24, 2023 pm 06:21 PM

Use the io/ioutil.WriteFile function to write a string to a file, and set the file permissions and indentation format. In the Go language, you can easily write a string to a file using the WriteFile function in the io/ioutil package. At the same time, we can also set file permissions and indentation format to meet different needs. Here is a sample code that demonstrates how to use the WriteFile function to write to a file and set permissions and indentation format: packagemainim

How does Java use NIO to optimize IO to implement file upload and download functions? How does Java use NIO to optimize IO to implement file upload and download functions? May 12, 2023 pm 09:31 PM

1. Some basic preparatory knowledge of NIO. BIO and NIO in the system of IO stream class in Java: https://blog.csdn.net/ZGL_cyy/article/details/104326458. JavaIO system and NIO and BIO system interview questions: https://blog. csdn.net/ZGL_cyy/article/details/122836368Why use NIO: Because the traditional IO file transfer rate is low, NIO is chosen for file download operations. Another advantage of NIO is that zero copy can reduce the duplication of data in memory and reduce the effect of CPU operations. Place

See all articles