python中的open和file

一直没弄明白python中open()和file()有什么区别,好像能用open()的地方,都可以使用file()来代替。它俩的原型也一样:

open(name[, mode[, buffering]]) -> file object
file(name[, mode[, buffering]]) -> file object

从文档来看,打开一个文件时,更推荐使用open。

因为open和file是内建函数,就查看了python的源码。才发现,原来file是一种类型,在Python/bltinmodule.c中可知, 它和float一样普通,通过type()验证,确实发现有file这个基本类型:

...
SETBUILTIN("file",                  &PyFile_Type);
SETBUILTIN("float",                 &PyFloat_Type);
...

而使用open()实际就是由python给构造一个file对象,而使用file()更像是自己调用构造函数来构造对象:

static PyObject *
builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
{
    return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
}

在fileobject.h中给出了PyFileObject结构的定义:

typedef struct {
    PyObject_HEAD
    FILE *f_fp;
    PyObject *f_name;
    PyObject *f_mode;
    int (*f_close)(FILE *); 
    int f_softspace;            /* Flag used by 'print' command */
    int f_binary;               /* Flag which indicates whether the file is
                               open in binary (1) or text (0) mode */
    char* f_buf;                /* Allocated readahead buffer */
    char* f_bufend;             /* Points after last occupied position */
    char* f_bufptr;             /* Current buffer position */
    char *f_setbuf;             /* Buffer for setbuf(3) and setvbuf(3) */
    int f_univ_newline;         /* Handle any newline convention */
    int f_newlinetypes;         /* Types of newlines seen */
    int f_skipnextlf;           /* Skip next \n */
    PyObject *f_encoding;
    PyObject *f_errors;
    PyObject *weakreflist; /* List of weak references */
    int unlocked_count;         /* Num. currently running sections of code
                               using f_fp with the GIL released. */
    int readable;
    int writable;
} PyFileObject;

而在fileobject.c中,给出了PyFileObject结构的初始值:

PyTypeObject PyFile_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "file",
    sizeof(PyFileObject),
    0,   
    (destructor)file_dealloc,                   /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_compare */
    (reprfunc)file_repr,                        /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    /* softspace is writable:  we must supply tp_setattro */
    PyObject_GenericSetAttr,                    /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
    file_doc,                                   /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    offsetof(PyFileObject, weakreflist),        /* tp_weaklistoffset */
    (getiterfunc)file_self,                     /* tp_iter */
    (iternextfunc)file_iternext,                /* tp_iternext */
    file_methods,                               /* tp_methods */
    file_memberlist,                            /* tp_members */
    file_getsetlist,                            /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    file_init,                                  /* tp_init */
    PyType_GenericAlloc,                        /* tp_alloc */
    file_new,                                   /* tp_new */
    PyObject_Del,                           /* tp_free */
};

其中,file_new()使用PyType_GenericAlloc()内存空间,file_init()调用open_the_file(),后者调用fopen(),打开文件。 所以,mode是"r" "w" "r+" "w+" "a+"跟fopen里的意义一样。新添加的"U",会在调用fopen()之前替换成"rb"。

modebehavior
r Open text file for reading. The stream is positioned at the beginning of the file.
r+ Open for reading and writing. The stream is positioned at the beginning of the file.
w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
发表于 2014年10月31日 16:43   评论:0   阅读:2487  



回到顶部

首页 | 关于我 | 关于本站 | 站内留言 | rss
python logo   django logo   tornado logo