Help reading binary data from files
John Machin
sjmachin at lexicon.net
Tue Feb 6 17:36:14 EST 2007
On Feb 7, 9:01 am, "jeff" <j... at kalikstein.com> wrote:
> I am stumped trying to read binary data from simple files. Here is a
> code snippet, where I am trying to simply print little-endian encoded
> data from files in a directory.
>
> for name in os.listdir(DOWNLOAD_DIR):
> filename = s.path.join(DOWNLOAD_DIR, name)
> if os.path.isfile(filename):
> f = open(filename, 'rb')
> while True:
> ele = unpack('<h', f.read(2))[0]
> print ele
>
> When the code runs, 0 is always the data printed, but the data files
> are not all zero.
>
> Any quick tips?
Looks to me like it should work -- at least until it hits the end of
the first file. What do you expect to happen at the end of the first
file?? Or did you so snippetise the code so that even if the missing
import statements are added back, it still won't get into the 2nd
file?
I suggest a few more print statements, so that you can see what is
happening.
Try something like this (untested):
f = open(filename, 'rb')
print "Opened", filename
while True:
buff = f.read(2)
if not buff: break # EOF
if len(buff) == 1:
print repr(buff), ord(buff)
break
ele = unpack('<h', buff)[0]
print repr(buff), ele
Print this, cut it out, and paste it to the inside of your hat:
*repr() is your friend*
HTH,
John
More information about the Python-list
mailing list