Python file modes detail

file-iopython

In Python, the following statements do not work:

f = open("ftmp", "rw")
print >> f, "python"

I get the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor

But with the following code it works:

g = open("ftmp", "r+")
print >> g, "python"

It looks like I need to revise the file modes. What are the deep intricacies of the file opening modes?

Best Answer

Better yet, let the documentation do it for you: http://docs.python.org/library/functions.html#open. Your issue in the question is that there is no "rw" mode... you probably want 'r+' as you wrote (or 'a+' if the file does not yet exist).