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

Xolve
  • 22,298
  • 21
  • 77
  • 125

4 Answers4

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

Jarret Hardie
  • 95,172
  • 10
  • 132
  • 126
  • 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 06 '12 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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • wow, how does the while(*s) and switch (*s++) work? oO From what I see, will it tear the string char by char? But what does the *++ mean? – Qwerty Mar 12 '13 at 11:46
  • 2
    @Qwerty: see [How does “while(*s++ = *t++)” work?](http://stackoverflow.com/questions/810129/how-does-whiles-t-work) to understand `*s`, `*s++` in C. – jfs Mar 12 '13 at 14:30
  • This is out of date; [`t` is also possible](https://stackoverflow.com/questions/23051062). – Karl Knechtel Jan 18 '23 at 09:04
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Xolve
  • 22,298
  • 21
  • 77
  • 125
  • See http://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 '09 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? – Jarret Hardie Mar 17 '09 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()
Golden Lion
  • 3,840
  • 2
  • 26
  • 35