Learn How To Write Bytes To A File In 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.

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

bytes(x, encoding, error)

Parameters

  • x
  • encoding
  • error

Return

bytes object

Example

>>> x=bytes(2)
>>> print(x)
b'\x00\x00'

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.

Output

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.

Output

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 modeAppend 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.

Output

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

Recommended Reading | 5 Ways to Convert bytes to string in Python

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.

Output

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.

Output

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.

Output

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.

Output

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.

1. Which type of file is useful to write bytes to a file?

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

2. What happens if we try to write bytes to a text file?

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

3. What type of error it shows when we write bytes to a text file?

It will show a TypeError.

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?

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ishraga Mustafa Awad Allam
Ishraga Mustafa Awad Allam
2 years ago

#By: Ishraga Mustafa Awad Allam. On:21-11- 2021.

import struct

fil = input(“Enter your file name, please: “)
file = open(fil, “wb”)

m = int(input(“Enter list size: “))
c = list(range(m))
for x in range(0, m):
 b = float(input(” Enter list item: “))
 c[x] = b 
print(c)  

b = struct.pack(‘<‘+’f’*len(c), *c)

with open(fil, “wb”) as file:
  file.write(b)
file.close()

file = open(fil, “rb”)
byte = file. read(4)
i = 0
y = list(range(m))
while byte: #byte=false at end of file.
x = struct.unpack(‘<f’, byte)
print(‘%8.3f’%x)
y[i] = x
byte = file. read(4)
i = i + 1
print(y)
file.close()

Pratik Kinage
Admin
2 years ago

That’s one unique way to do it!