Python文件模式详细信息[重复]

rbl8hiat  于 2023-06-04  发布在  Python
关注(0)|答案(4)|浏览(418)

此问题已在此处有答案

Difference between modes a, a+, w, w+, and r+ in built-in open function?(9个回答)
Python file open function modes(2个答案)
5个月前关闭。
在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"

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

**更新:**Python 3,不支持rw模式。你会得到错误:

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

pexxcrt2

pexxcrt21#

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

4xy9mtcn

4xy9mtcn2#

作为@Jarret Hardie的回答的补充,下面是Python如何在函数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;

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

o4tp2gmn

o4tp2gmn3#

事实上,这是可以的,但是我在下面的代码(对于S60上的Python)的第42和45行中发现了套接字上的“rw”模式:
http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html

a9wyjsp7

a9wyjsp74#

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

相关问题