Python file modes detail

后端 未结 3 1028
轻奢々
轻奢々 2021-02-03 10:28

In Python, the following statements do not work:

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

I get the error:

Trace         


        
3条回答
  •  天涯浪人
    2021-02-03 11:05

    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.

提交回复
热议问题