开发者

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

开发者 https://www.devze.com 2023-03-11 23:55 出处:网络
I have a large binary file of ieee 32bit floating point numbers. In python I use: f = file.read(4) while f !=\'\':

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 b开发者_运维问答e a string of size 4.

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

What could be causing this?


Did you open the file in binary mode?

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


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?


See this page: file.read

Specifically

Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.

0

精彩评论

暂无评论...
验证码 换一张
取 消