LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   python read binary file into array (https://www.linuxquestions.org/questions/linux-newbie-8/python-read-binary-file-into-array-4175547091/)

simhumcon 07-02-2015 09:44 PM

python read binary file into array
 
hello pros!
im quite a newbie in python. please help me out!

so i have a hex file, that is about 2821 sector size. i want to create an array for every 128 sectors. is there an example to do this?

what ive done so far is, i read the hex file containment and added a comma after every 2 characters, to separate the values

Code:

f = open(file_location, "rb")
imgData=f.read(1444352)
f.close()

filebyte = imgData.encode('hex')

def insert_newlines(string, every=2):
    lines = []
    for i in xrange(0, len(string), every):
        lines.append(string[i:i+every])
    return ','.join(lines)

content = insert_newlines(filebyte)

real_content = content.split(',')

print real_content


dslackw 07-02-2015 10:05 PM

Code:

f = open("binary", "rb")
r = f.read()
f.close()

sector = []

c = 0
for s in r:
    sector.append(s)
    c += 1
    if c == 128:
        sector.append(",")
        c = 0

print sector

If I understand this might give you the idea.

simhumcon 07-03-2015 03:09 AM

hi! that is what exactly what im trying to do. now im stuck else where

so, now, i have a list of hex values that i want to pack using struct.pack. so here's what i did after reading from the hex file

Code:


import sys,getopt

filename = file_location
blocksize = 1444352

opts,args = getopt.getopt(sys.argv[1:],'f:b:')
for o,a in opts:
        if o == '-f':
                filename = a
        if o == '-b':
                blocksize = a

offset = 0
with open(filename,"rb") as f:
        block = f.read(blocksize)
        str = ""
        for ch in block:
                str += hex(ord(ch))+" "


sector = []
c = 0
for s in str.split(' ') :
    sector.append(s)
    c += 1
    if c == 128 :
        sector.append("")
        c = 0
        sector  = ', '.join(sector)
        print sector
        #struct.pack('B', sector)
        sector = sector.split(',')
        for items in sector[0:127] :
            items = int(items, 16)
            #print items

        struct.pack('B', sector)
        break



but i keep getting error message "struct error : cannot convert argument to integer"
but ive already converted to int


All times are GMT -5. The time now is 12:25 PM.