You are opening for writing incorrectly, looks like it.
Update: Looks like you have removed the code that didn't work from your original post since you fixed the problem. You should probably re-post it. Unless somebody really wants to delete this thread (not what usually happens).