简体   繁体   中英

unpack binary file in python 3

Could you please help to unpack the binary file in Python 3? It is an image 2580*7839 size, 4-byte float. What I had in the code for Python 2 and it worked, but not in Python 3.

bformat= ">%sf"
ns = 2580*7839*4
#open file f
byte_arr=f.read(ns)
unpacked_bytes = unpack(bformat % (ns/4), byte_arr)
data=np.array(unpacked_bytes).reshape(7839,2580)
print ('min value', data.min())
print ('max value', data.max())

I get the error message "struct.error: bad char in struct format"

Thanks!

What about using struct?

import struct

f0 = struct.unpack('>f', f.read(4))[0]
f1 = struct.unpack('>f', f.read(4))[0]
f2 = struct.unpack('>f', f.read(4))[0]
....

of better in the loop

for i in range(0, 2580*7839):
    ff = struct.unpack('>f', f.read(4))[0]
    print(i,ff)

it will break somewhere and you'll know where

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM