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 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 是什么?
您可以通过调用 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();
此页面声称 API 是:
PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd);
不确定这是否意味着无法让 Python 从文件名打开文件,但在 C 语言中,这对你自己来说应该是微不足道的。