简体   繁体   中英

Python f.read not reading the correct number of bytes

I have code that is supposed to read 4 bytes but it is only reading 3 sometimes:

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? Thanks!

You're assuming read does something it does not. As its documentation tells you:

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

it reads at most size bytes

If you need exactly size bytes, you'll have to create a wrapper function.


Here's a (not thoroughly tested) example 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

As Mark Dickinson mentioned in the comments, if you're on Windows, make sure you're reading in binary mode - otherwise you risk read ing your (binary) data wrong.

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