Python write bytes to files

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.

Читайте также:  Python subprocess run grep

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.

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?

Источник

Write Bytes to a File in Python

Write Bytes to a File in Python

  1. Write Bytes to a File in Python
  2. Write a Byte Array to a File in Python
  3. Write BytesIO Objects to a Binary File

In this tutorial, we will introduce how to write bytes to a binary file in Python.

Binary files contain strings of type bytes. When we read a binary file, an object of type bytes is returned. In Python, bytes are represented using hexadecimal digits. They are prefixed with the b character, which indicates that they are bytes.

Write Bytes to a File in Python

To write bytes to a file, we will first create a file object using the open() function and provide the file’s path. The file should be opened in the wb mode, which specifies the write mode in binary files. The following code shows how we can write bytes to a file.

data = b'\xC3\xA9'  with open("test.bin", "wb") as f:  f.write(data) 

We can also use the append mode — a when we need to add more data at the end of the existing file. For example:

data = b'\xC3\xA9'  with open("test.bin", "ab") as f:  f.write(data) 

To write bytes at a specific position, we can use the seek() function that specifies the file pointer’s position to read and write data. For example:

data = b'\xC3\xA9'  with open("test.bin", "wb") as f:  f.seek(2)  f.write(data) 

Write a Byte Array to a File in Python

We can create a byte array using the bytearray() function. It returns a mutable bytearray object. We can also convert it to bytes to make it immutable. In the following example, we write a byte array to a file.

arr = bytearray([1,2,5]) b_arr = bytes(arr)  with open("test.bin", "wb") as f:  f.write(b_arr) 

Write BytesIO Objects to a Binary File

The io module allows us to extend input-output functions and classes related to file handling. It is used to store bytes and data in chunks of the memory buffer and also allows us to work with the Unicode data. The getbuffer() method of the BytesIO class is used here to fetch a read-write view of the object. See the following code.

from io import BytesIO  bytesio_o = BytesIO(b"\xC3\xA9")  with open("test.bin", "wb") as f:  f.write(bytesio_o.getbuffer()) 

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

Related Article — Python File

Источник

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