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 =
>>> len(s)
>>> f.close()
>>> f = open(filename, "rb")
>>> s =
>>> len(s)
>>> 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.

Sunday, November 15, 2009

Not short circuited

If you want to do the following:

boolean pass = true;
pass = pass && test1();
pass = pass && test2();

It is NOT equivalent to the following:

boolean pass = true;
pass &= test1();
pass &= test2();

Because the &= operator is not short circuited. It compiles and works just fine for booleans, but it is a bitwise operator at heart and only works for booleans out of sympathy.

What we need is a &&= operator.