Thursday, June 10, 2021

Read a binary file using Python

 Hi,

Today, I have to write a python script to verify the data present in it. 

We are expecting a fixed pattern from 0 to 63, until end of the file. So the snipper can be seen below.


The size of file is around 272 KB, to check if there is any value missing would be nightmare.

Hence I wrote a small python script which checks the data integrity and prints the data mismatch string on console.

import os

f = open("try.bin", 'rb')

print("Reading to buffer")

count = 0

pages = 0;


while True:

    count = 0

    buffer = f.read(64)

    if not buffer:

        break

    while(count < 64):

        if(buffer[count] != count):

            print("data mismatch")

        count = count + 1

    pages = pages + 1

    if((pages % 16) == 0):

        print("\n", end = '')

print ("No of pages", pages)

f.close()


Hope this helps for you. 

This is being tested with Python 3.7.9

Thank you for reading.


No comments:

Post a Comment