How to read (or write) binary data in Python?
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 -
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)
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'
Write to binary file
Thewb 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()
Output
After running the file, the file will be visible in the set path, that is, the E drive -
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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 <key>slmgr/ipk<key> Download the universal ticket from here and extract the downloaded file. Now enter the following code in Powershell (Get-ItemProper

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

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.

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

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

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

The concept of IO stream can be initially understood as the transmission of data. We put a set of data into: 1234567 and transfer them from the hello file to the haha file. If you use the program method to transfer, you need to transfer them one by one. That is to say, it is a byte-by-byte transmission. We can only pass in or read one byte at a time. This is the general process of the io stream. The io stream can read any type of file. Such as: text files, pictures, songs mp3, videos, etc. Because the io stream is read byte by byte, we need to use the byte single-byte variable to get the length. If you get too much content, you need to use the corresponding array. The method corresponding to the io stream needs to be written in all io stream methods.
