Write binary data to file python

Write Binary File in Python

We created a byte_list using a sequence of values from 0 to 255 in binary form.

The bytearray() function is a built-in function in Python that takes an iterable to convert it into an array of bytes.It is an object constructor for a mutable array of bytes, like a list , but unordered. From an iterable of integers, it only accepts values in the range(256) , or the function throws a ValueError: byte must be in range(0, 256) .

We used the bytearray() function to convert the byte_list to the byte_array . To successfully write the byte_array to the file, we used Python’s try-except control flow statement. It handles errors and exceptions without disrupting the flow of the program.

We used the with keyword to wrap the code block of writing the byte_array to the bytes_array.txt file. Next, we used the open() function to open a file for reading, or writing is a built-in function in Python. It took two arguments: the filename and the mode.

The mode is an optional argument. It defaults to r (read) if it’s not specified. We specified the mode as wb to create or truncate the existing file named bytes_array.txt as binary. The write() function wrote the byte_array to the bytes_array.txt file.

Use bytes() Function

To write a binary file in Python:

  • Use the bytes() function to convert the list of bytes to a bytes type object.
  • Use a with clause with open() the method in write binary mode( wb )
  • Use write() method to write the byte_array to the file.

Источник

Learn How To Write Bytes To A File In Python

write bytes to file python

Here we are going to learn about how to write bytes to a file in python. With that, we will learn many things about file handling. This article is going to be very interesting. And also, we will come to know about how to write byte an array to a file in python? Byte IO objects to a binary file. Let us learn about writing bytes in a detailed manner.

Generally, we are using a binary file to write bytes. File handling contains two types of files. One is a text file, and the other is a binary file. Both the files contain different modes. The text file contains open, read, write, append, and close modes. The same modes are available in a binary file.

Читайте также:  Section heading in html

What are bytes in python?

Before learning about how to write bytes, first, we will learn about what is bytes?

Bytes() is a function that returns a bytes object. It is useful to convert objects into byte objects. Bytes will create an empty object of the specified size if the object is not given. Bytes are prefixed with a letter b.

Syntax

Parameters

Return

Example

In this example, I’m giving a byte size two.

How to write bytes to a file in python?

We are using b as a prefix to write bytes. Either single or double quotes are useful to mention the bytes. We are always using the binary file to write bytes.

Writing bytes using write mode in a binary file

byte=b"This is Python Pool.\nHere You can learn Python very easily.\nThis web is user friendly." with open("file.bin","wb") as f: f.write(byte) f.close() print("The details you have given are successfully written to the corresponding file. You can open a file to check")

First, create a variable byte. This variable contains the data that has to write in a file. Next opening a file in binary write format. It will open the file if it already exists. Suppose the file does not exist. It will create a new file and save the given data. The file is opened in a write mode.

So the data will be overwritten if the data already exists in a file, next to writing bytes to the data. Closing a corresponding file. If the data is successfully written, it will show the message given in a print statement. Otherwise, it will show an error.

The details you have given are successfully written to the corresponding file. You can open a file to check

write bytes to a file in python

Writing bytes using append mode in a binary file

byte=b"\nHere you can interact with us if you have any doubts." with open("file.bin","ab") as f: f.write(byte) f.close() print("The details you have given are successfully added to the corresponding file. You can open a file to check")

First, create a variable byte. This variable contains the data that has to write in a file—next opening a file in binary append format. The text will be added at the end of the file. Append mode does not overwrite.

Next, appending the data. Closing the file. If the data is successfully added, it will show the message given in a print statement. Otherwise, it will show an error.

The details you have given are successfully added to the corresponding file. You can open a file to check

Writing bytes using append mode in a binary file

Difference between write mode and append mode

Now some of us got a confusion what is the difference between write and append mode. Both are useful to write then why specifically append and write. So, the below tabular column is useful to the people who got the above question.

Читайте также:  Питон как задать функцию
Write mode Append mode
When we are using write mode, the content in the file will be overwritten. When we are using append mode, the content is added to the existing content.
The letter w is useful to declare write mode. In binary, wb is useful. The letter a is useful to declare append mode. In binary files, ab is useful.
The new file is created if the file does not exist. The new file is created if the file does not exist.

How to write a byte array to a file in Python?

data_array = ([6,8,9,0,4,7,1]) byte_data = bytes(data_array) with open("sample.bin","wb") as f: f.write(byte_data) f.close() print("Your array was saved in a corresponding file but it was encoded")

The data_array variable contains an array.bytes(data_array) are useful to encode the array. Always it saves data in an encoded form. Closing a file.

Your array was saved in a corresponding file but it was encoded

How to write ByteIO objects in a binary file?

from io import BytesIO bytes_IO = BytesIO(b"Python is very intersting\nLearn Python in Python pool") with open("file.bin", "wb") as f: f.write(bytes_IO.getbuffer()) f.close() print("The message is added successfully")

From io importing BytesIO. A variable bytes_IO holds the data. Opening a file. Writing the bytes IO to the file. Closing the file. Suppose this process is completed successfully. It will execute the print statement.

The message is added successfully

How to write ByteIO objects in a binary file?

Append Byte IO objects

from io import BytesIO bytes_IO = BytesIO(b"\nPython is a user-friendly") with open("file.bin", "ab") as f: f.write(bytes_IO.getbuffer()) f.close() print("The message is added successfully")

From io importing BytesIO. A variable bytes_IO holds the data. Opening a file. Appending the bytes IO to the file. Closing the file. Suppose this process is completed successfully. It will execute the print statement.

The message is added successfully

Append Byte IO objects

How to write hex bytes to a file

byte=b'\xde\xad\xbe\xef' data=b'\xde\xad\xbe\xef'.hex() with open("file1.bin","wb") as f: f.write(byte) f.close() print("The hex data", data, " is stored but it is encoded in the file")

A variable byte stores the hex bytes. Opening a file. They are in a file; the texts are in encoded form. To decode, we have to give the current encoding.

The hex data dead is stored but it is encoded in the file

How to write random bytes to a file

import os size=5 result = os.urandom(size) with open("file1.bin","wb") as f: f.write(result) f.close() print("The random byte",result,"is stored but it is encoded in the file")

Importing os to generate random bytes. urandom is useful to generate a random byte. Opening a file and writing the random byte to file.

The random byte b'A\xacy\xaf\xf9' is stored but it is encoded in the file

What happens if we add a bytes to a text file?

The common question we all got now is why are we using a binary file to add the bytes? Why are we not using a text file? Let us try to add the bytes to a text file. Let us see what will happen with the following code.

byte=b"This is Python Pool.\nHere You can learn Python very easily.\nThis web is user friendly." with open("file.txt","w") as f: f.write(byte) f.close()

Now we wrote the code for a text file. Let us run this code.

Traceback (most recent call last):
File "C:\Users\priyalakshmi\AppData\Local\Programs\Python\Python39\write bytes.py", line 3, in
f.write(byte)
TypeError: write() argument must be str, not bytes

So now it is easy for us to understand why are we using a binary file. Text file only accepts a string.

Читайте также:  Your first JavaScript file

A binary mode file is useful to write bytes to a file.

It will show an error if we try to write bytes to a text file.

In the End

Here we came to the end of the article. We have learned an interesting topic in this article. I hope this article is easy to understand. We have learned how to add bytes to a file? How to write a byte array to a file? How to write byte io objects to a file? And why are we using a binary file to add bytes?

Источник

How do I read (or write) binary data in Python?

The Binary Files are not huma-readable and the content is unrecognizable. The actual output was bigger. We have shown only some part below.

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- 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 a Binary File

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

Note − The Binary Files are not huma-readable and the content is unrecognizable

Let’s see the complete example. Here, the file will get stored in E drive with the name

Example

# 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 is visible in the set path i.e. E drive −

Источник

Оцените статью