13

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?

Update: Python 3, doesn't allow "rw" mode. You would get the error:

ValueError: must have exactly one of create/read/write/append mode

0

4 Answers 4

17

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).

1
  • 13
    The documentation is insufficient. It doesn't say that you can't have r and w. It doesn't say what the difference between w+ and w is (what exactly does "updating" mean?), and it doesn't say if a seeks to the end of the file (I assume it does, but maybe not). And it doesn't give a clear way to open a file for reading and writing, at the beginning, without truncating it.
    – Timmmm
    Oct 6, 2012 at 12:54
12

As an addition to @Jarret Hardie's answer here's how Python check file mode in the function fileio_init():

s = mode;
while (*s) {
    switch (*s++) {
    case 'r':
        if (rwa) {
        bad_mode:
            PyErr_SetString(PyExc_ValueError,
                    "Must have exactly one of read/write/append mode");
            goto error;
        }
        rwa = 1;
        self->readable = 1;
        break;
    case 'w':
        if (rwa)
            goto bad_mode;
        rwa = 1;
        self->writable = 1;
        flags |= O_CREAT | O_TRUNC;
        break;
    case 'a':
        if (rwa)
            goto bad_mode;
        rwa = 1;
        self->writable = 1;
        flags |= O_CREAT;
        append = 1;
        break;
    case 'b':
        break;
    case '+':
        if (plus)
            goto bad_mode;
        self->readable = self->writable = 1;
        plus = 1;
        break;
    default:
        PyErr_Format(PyExc_ValueError,
                 "invalid mode: %.200s", mode);
        goto error;
    }
}

if (!rwa)
    goto bad_mode;

That is: only "rwab+" characters are allowed; there must be exactly one of "rwa", at most one '+' and 'b' is a noop.

3
0

In fact, this is okay, but I found an "rw" mode on the socket in following code (for Python on S60) at lines 42 and 45:

http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html

2
  • See docs.python.org/library/socket.html#module-socket. "Note Some behavior may be platform dependent, since calls are made to the operating system socket APIs." So it sounds like an S60-specific feature.
    – S.Lott
    Mar 17, 2009 at 19:46
  • I'd also point out that r+ and a+ enable both read and write. Open a file with r+, and you can seek() around the file at will, overwriting or appending content. Is there a feature that you're expecting that the '+' series doesn't provide? Mar 17, 2009 at 23:10
0

https://www.geeksforgeeks.org/python-append-to-a-file/

use the append if the file exists and write if it does not.

 import pathlib
 file = pathlib.Path("guru99.txt")
 if file.exists ():
      file1 = open("myfile.txt", "a")  # append mode  
 else:
      file1 = open("myfile.txt", "w")  # append mode


file1.write("Today \n")
file1.close()

Not the answer you're looking for? Browse other questions tagged or ask your own question.