file object, details of modes and some issues.

Jeff Epler jepler at unpythonic.net
Tue Aug 26 18:20:13 CEST 2003


Here's what I get on my system:
    >>> f = file("xyzzy", "w")
    >>> f.read()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    IOError: [Errno 9] Bad file descriptor
    >>> f.write(' ')
    >>> f.read()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    IOError: [Errno 9] Bad file descriptor

Python relies fairly directly on the C standard library for correct
behavior when it comes to file objects.  I suspect that the following C
program will also "succeed" on your system:

    #include <stdio.h>
    int main(void) {
        FILE *f = fopen("xyzzy", "w");
        char buf[2];
        char *res;
        fputs(" ", f);
        res = fgets(buf, 2, f);
        if(!res) {
            perror("fgets");
            return 1;
        }
        return 0;
    }

On my system, it does given an error:
    $ gcc simon.c
    $ ./a.out
    fgets: Bad file descriptor
    $ echo $?
    1
If the C program prints an error message like above, but Python does not
raise an exception on the mentioned code, then there's a Python bug.
Otherwise, if the C program executes on your system without printing an
error and returns the 0 (success) exit code, then the problem is the
poor quality of your platform's stdio implementation.

Jeff
PS relevant text from the fgets manpage on my system:
    gets() and fgets() return s on success, and NULL on error or when
    end of file occurs while no characters have been read.
and from fopen:
    w   Truncate file to zero length or create text file for writing.
        The stream is positioned at the beginning of the file.






More information about the Python-list mailing list