本文介绍了Python文件模式的细节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ $ $ $ $ $ $ $ $
print>> f,python

我得到这个错误:

  Traceback(最近一次调用的最后一个):
在< module>中,第1行的文件< stdin>
IOError:[Errno 9]错误的文件描述符

但是使用下面的代码:

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

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



  s = mode; (* s){
switch(* s ++){
case'r':
if(rwa){
bad_mode:
PyErr_SetString( PyExc_ValueError,
必须正好有一个读/写/附加模式);
转到错误;
}
rwa = 1;
自助>可读= 1;
break;
case'w':
if(rwa)
goto bad_mode;
rwa = 1;
自我>可写= 1;
flags | = O_CREAT | O_TRUNC;
break;
case'a':
if(rwa)
goto bad_mode;
rwa = 1;
自我>可写= 1;
flags | = O_CREAT;
append = 1;
break;
案例'b':
break;
case'+':
if(plus)
goto bad_mode;
自助>可读=自>可写= 1;
plus = 1;
break;
默认值:
PyErr_Format(PyExc_ValueError,
invalid mode:%.200s,mode);
转到错误;



if(!rwa)
goto bad_mode;

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


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?

解决方案

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.

这篇关于Python文件模式的细节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:20