Python What Is the Difference Between Reading as Binary
In this Python tutorial, we will acquire how to read a binary file in python, and also we will cover these topics:
- How to read a binary file to an array in Python
- How to read a binary file into a byte array in Python
- How to read a binary file line by line in Python
- Python read a binary file to Ascii
- How to read a binary file into a NumPy array in Python
- How to read a binary file into CSV in Python
Python read a binary file
Hither, we will see how to read a binary file in Python.
- Before reading a file we have to write the file. In this case, I have opened a file using file = open("document.bin","wb") and used the "wb" mode to write the binary file.
- The certificate.bin is the proper noun of the file.
- I have taken a variable equally a sentence and assigned a sentence "This is good", To decode the sentence, I accept used sentence = bytearray("This is skilful".encode("ascii")).
- And to write the sentence in the file, I have used the file.write() method.
- The write() is used to write the specified text to the file. And then to shut the file, I take used the file.close().
Case to write the file:
file = open("certificate.bin","wb") sentence = bytearray("This is adept".encode("ascii")) file.write(sentence) file.close()
- To read the file, I take taken the already created file certificate.bin and used the "rb" style to read the binary file.
- The document.bin is the file name. And, I accept using the read() method. The read() method returns the specified number of bytes from the file.
Example to read the file:
file = open("certificate.bin","rb") print(file.read(4)) file.shut()
In this output, y'all tin can see that I have used print(file.read(4)). Here, from the sentence, it will read only four words. As shown in the output.
You may similar Python Pandas CSV Tutorial and File does non exist Python.
Python read a binary file to an assortment
Here, nosotros tin see how to read a binary file to an array in Python.
- In this example, I accept opened a file as array.bin and used the "wb" mode to write the binary file. The assortment.bin is the name of the file.
- And assigned an array as num=[2,iv,half dozen,8,10] to get the array in byte converted format, I take used bytearray(). The bytearray() method returns the byte assortment objects.
- To writes the array in the file, I have used the file.write(). And file.shut() to shut the file.
Example to write an array to the file:
file=open("array.bin","wb") num=[two,4,half dozen,eight,10] array=bytearray(num) file.write(array) file.close()
- To read the written array from the file, I take used the same file i.e,file=open("assortment.bin","rb").
- The "rb" mode is used to read the array from the file.
- The list() part is used to create the list object number=listing(file.read(3)). The file.read() is used to read the bytes from the file.
- The file.read(3) is used to read-only three numbers from the array. The file.close() is used to close the file.
Example to read an array from the file:
file=open("assortment.bin","rb") number=list(file.read(3)) print (number) file.close()
To get the output, I take used print(number). And to close the file, I have used file.close(). In the below screenshot you tin can see the output.
- How to Convert Python string to byte array with Examples
- Python Array with Examples
- Create an empty array in Python
Python read a binary file into a byte array
Now, we tin see how to read a binary file into a byte array in Python.
- In this example, I accept opened a file called sonu.bin and "rb" fashion is used to read a binary file, and sonu.bin is the proper name of the file. Here, I have stored some information in the sonu.bin file.
- The byte = file.read(3) is used to read the file, and file.read(3) is used to read only 3 bytes from the file.
- The while loop is used to read and iterate all the bytes from the file.
Example:
file = open("sonu.bin", "rb") byte = file.read(3) while byte: print(byte) byte = file.read(3)
To read the byte from the file, I have used print(byte). You can refer to the below screenshot for the output.
Python read a binary file line by line
Here, nosotros can meet how to read a binary file line by line in Python.
- In this example, I have taken a line as lines=["Welcome to python guides\n"] and open a file named every bit file=open up("document1.txt","wb") document1.txt is the filename.
- The "wb" is the mode used to write the binary files. The file.writelines(lines) is used to write the lines from the file.
- The writelines() returns the sequence of string to the file. The file.close() method is used to close the file.
Example to write the file:
lines=["Welcome to python guides\n"] file=open("document1.txt","wb") file.writelines(lines) file.close()
- To read the written file, I have used the same filename as document1.txt, I have used file=open up("document1.txt","rb") to open the file, "rb" mode is used to read the binary file and, To read the line from the file I take used line=file.readline().
- The readline() returns ane line from the file.
Example to read the file:
file=open("document1.txt","rb") line=file.readline() print(line) file.close()
To go the output, impress(line) is used and lastly to shut the file, I have used file.close().
Python read a binary file to Ascii
At present, we can see how to read a binary file to Ascii in Python.
- In this example, I accept opened a file named test.bin using file = open('test.bin', 'wb'), The 'wb' manner is used to write the binary file and I take taken a variable as a sentence and assigned a sentence = 'Hello Python'. To encode the judgement.
- I have used file_encode = sentence.encode('ASCII'). To write the encoded sentence in the file, I have used the file.write(file_encode).
- The file.seek() method returns the new position. To read the written file, I have used the file.read() which returns a byte from the file.
- Then to convert the binary sentence into Ascii, I accept used new_sentence = bdata. decode('ASCII').
Example:
file = open up('exam.bin', 'wb') sentence = 'Hello Python' file_encode = sentence.encode('ASCII') file.write(file_encode) file.seek(0) bdata = file.read() print('Binary judgement', bdata) new_sentence = bdata.decode('ASCII') print('ASCII sentence', new_sentence)
To get the output as an encoded sentence, I have used impress('ASCII sentence', new_sentence). You lot tin refer to the below screenshot for the output.
Python read a binary file into a NumPy array
Hither, we can see how to read a binary file into a numpy assortment in Python.
- In this example, I have imported a module chosen NumPy. The array = np.array([2,8,7]) is used to create an array, The .tofile is used to write all the array to the file. The assortment.bin is the name of the binary file.
- The np.fromfile is used to construct an array from the data in the file. The dtype=np.int8 is the datatype object. The output of the array changes if we change np.int8 to int32 or int64.
Example:
import numpy as np assortment = np.array([2,8,7]).tofile("array.bin") print(np.fromfile("array.bin", dtype=np.int8))
To go the output, I have used print(np.fromfile("array.bin", dtype=np.int8)). The beneath screenshot shows the output.
Python read a binary file into CSV
Hither, we can run into how to read binary file into csv in Python.
- In this example, I have imported a module called CSV. The CSV module is a comma-separated value module. Information technology is used to read and write tabular information in CSV format.
- I have opened a file called lock.bin and "w" mode is used to write the file author = csv.writer(f) is used to write the objects in the file. The lock.bin is the name of the file.
- The writer() returns the write object which converts data into a string.
- The author.writerows is used to write all the rows into the file. To shut the file, f.close() is used.
Example to write the csv file:
import csv f = open("lock.bin", "w") writer = csv.author(f) writer.writerows([["a", 1], ["b", 2], ["c", 3], ["d",iv]]) f.close()
To read the CSV file, I have opened the file lock.bin in which information is already written, The 'r' way is used to read the file. To read the CSV file, I have used reader = csv.reader(file) to return a list of rows from the file.
Example to read the csv file:
import csv with open('lock.bin', 'r') every bit file: reader = csv.reader(file) for row in reader: print(row)
To become the output I have used print(row). The beneath screenshot shows the output.
Yous may like the post-obit Python tutorials:
- How to draw a shape in python using Turtle
- Python ask for user input (Examples)
- How to Convert Python cord to byte assortment with Examples
- Python pass by reference or value with examples
- Python select from a list + Examples
- Union of sets Python + Examples
- Introduction to Python Interface
- How to convert a Cord to DateTime in Python
- Python listing comprehension using if-else
In this tutorial we accept learned nigh Python read a binary file, besides we have covered these topics:
- Python read a binary file to an array
- Python read a binary file into a byte array
- Python read a binary file line past line
- Python read a binary file to Ascii
- Python read a binary file into a NumPy array
- Python read a binary file into CSV
Source: https://pythonguides.com/python-read-a-binary-file/
Post a Comment for "Python What Is the Difference Between Reading as Binary"