Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python read(4) returning a string of length 1 not 4

I have a large binary file of ieee 32bit floating point numbers.

In python I use:

f = file.read(4)
    while f !='':
        if len(f) == 4:
            data =struct.unpack('>f', f)
            print data
f = file.read(4)

to read it 4 bytes at a time

However, occasionally f would be size 1, and struct.unpack would complain that its input must be a string of size 4.

The filesize is divisible by 4, and this happens multiple times within the file.

What could be causing this?

like image 508
Razor Storm Avatar asked Jul 24 '26 22:07

Razor Storm


2 Answers

Did you open the file in binary mode?

Anyway, a much better way to read your file is to use array.fromfile() or NumPy.

like image 107
Sven Marnach Avatar answered Jul 27 '26 11:07

Sven Marnach


First of all, i recommend against the use of the word file as a variable, as it is a __builtin__ function.

Secondly, binary mode or ascii mode?

like image 29
Pwnna Avatar answered Jul 27 '26 10:07

Pwnna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!