【问题标题】:File I/O in the Python 3 C APIPython 3 C API 中的文件 I/O
【发布时间】:2009-05-22 14:23:39
【问题描述】:

Python 3.0 中的 C API 已更改(弃用)文件对象的许多函数。

在 2.X 之前,您可以使用

PyObject* PyFile_FromString(char *filename, char *mode)

创建一个 Python 文件对象,例如:

PyObject *myFile = PyFile_FromString("test.txt", "r");

...但是这样的功能在 Python 3.0 中不再存在。 与这种调用等效的 Python 3.0 是什么?

【问题讨论】:

    标签: python python-3.x python-c-api


    【解决方案1】:

    您可以通过调用 io 模块以旧的(新的?)方式来实现。

    此代码有效,但不进行错误检查。有关说明,请参阅文档。

    PyObject *ioMod, *openedFile;
    
    PyGILState_STATE gilState = PyGILState_Ensure();
    
    ioMod = PyImport_ImportModule("io");
    
    openedFile = PyObject_CallMethod(ioMod, "open", "ss", "foo.txt", "wb");
    Py_DECREF(ioMod);
    
    PyObject_CallMethod(openedFile, "write", "y", "Written from Python C API!\n");
    PyObject_CallMethod(openedFile, "flush", NULL);
    PyObject_CallMethod(openedFile, "close", NULL);
    Py_DECREF(openedFile);
    
    PyGILState_Release(gilState);
    Py_Finalize();
    

    【讨论】:

    • 就没有别的办法了吗?与问题中显示的示例相比,这似乎很麻烦。
    • 什么是"ss"
    【解决方案2】:

    This page 声称 API 是:

    PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd);
    

    不确定这是否意味着无法让 Python 从文件名中打开文件,但在 C 语言中,您自己应该很容易做到这一点。

    【讨论】:

      猜你喜欢
      • 2015-11-28
      • 2011-08-07
      • 2011-09-07
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2014-03-17
      • 1970-01-01
      相关资源
      最近更新 更多