Python文件模式细节

时间:2009-03-17 14:32:48

标签: python file-io

在Python中,以下语句不起作用:

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

我收到错误:

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

但是使用以下代码可以工作:

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

看起来我需要修改文件模式。文件打开模式的深层复杂性是什么?

4 个答案:

答案 0 :(得分:17)

更好的是,让文档为您完成:http://docs.python.org/library/functions.html#open。你在问题中的问题是没有“rw”模式......你可能在你写的时候想要'r +'(或者如果文件还不存在则需要'a +')。

答案 1 :(得分:12)

作为@Jarret Hardie's answer的补充,这里是函数fileio_init()中Python检查文件模式的方式:

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;

即:仅允许"rwab+"个字符;必须只有一个"rwa",最多一个'+''b'是noop。

答案 2 :(得分:0)

事实上,这没关系,但是我在第42和45行的代码(S60上的Python)中找到了套接字上的“rw”模式:

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

答案 3 :(得分: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()