Python f.read does not read the correct number of bytes

I have code that should read 4 bytes, but sometimes it only reads 3:

f = open('test.sgy', 'r+')
f.seek(99716)
AAA = f.read(4)
BBB = f.read(4)
CCC = f.read(4)
print len(AAA)
print len(BBB)
print len(CCC)

exit()

And this program returns: 4 3 4

What am I doing wrong? Thank!

+4
source share
1 answer

You assume you are readdoing something that is not there. As its documentation says:

read(...)
    read([size]) -> read at most size bytes, returned as a string.

it reads no more than size bytes

If you need exactly a sizebyte, you need to create a wrapper function.


Here is an example (not fully tested) that you can adapt:

def read_exactly( fd, size ):
    data=""
    remaining= size
    while remaining>0:      #or simply "while remaining", if you'd like
        newdata= fd.read(remaining)
        if len(newdata)==0: #problem
            raise IOError("Failed to read enough data")
        data+=newdata
        remaining-= len(newdata)
    return data

, Windows, , - read () .

+5

All Articles