Python f.read not reading the correct number of bytes -
i have code supposed read 4 bytes 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 program returns: 4 3 4
what doing wrong? thanks!
you're assuming read
not. documentation tells you:
read(...) read([size]) -> read @ size bytes, returned string.
it reads at most size
bytes
if need exactly size
bytes, you'll have create wrapper function.
here's (not thoroughly tested) example can adapt:
def read_exactly( fd, size ): data="" remaining= size while remaining>0: #or "while remaining", if you'd newdata= fd.read(remaining) if len(newdata)==0: #problem raise ioerror("failed read enough data") data+=newdata remaining-= len(newdata) return data
as mark dickinson mentioned in comments, if you're on windows, make sure you're reading in binary mode - otherwise risk read
ing (binary) data wrong.
Comments
Post a Comment