Friday, November 20, 2009

Python 2.4 problem with reading binary files

In Python 2.4, you must specify "rb" as the mode for reading binary files. In Python 2.6 you can just say "r" and it will work.

Python 2.4:
>>> f = open(filename, "r")
>>> s = f.read()
>>> len(s)
114
>>> f.close()
>>> f = open(filename, "rb")
>>> s = f.read()
>>> len(s)
230
>>> f.close()
The problem is that it only reads part of the file. I don't know why it thinks the file is done in the middle like that, but to fix it, specify "rb" instead of "r".

I ran into this problem writing a program in Python 2.6 using just "r" and didn't run into the problem until I tried running it in Python 2.4.

1 comment:

Andy said...

always specify 'b' when reading/writing binary files. Otherwise, behavior associated with bytes that are 13 and 10 will have platform-dependent bugs.