Python 3 C API中的文件I/O.

Vic*_*rti 8 python python-c-api python-3.x

Python 3.0中的C API已经更改(不建议使用)文件对象的许多功能.

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

PyObject* PyFile_FromString(char *filename, char *mode)
Run Code Online (Sandbox Code Playgroud)

创建Python文件对象,例如:

PyObject *myFile = PyFile_FromString("test.txt", "r");
Run Code Online (Sandbox Code Playgroud)

...但是Python 3.0中不再存在这样的功能.什么是Python 3.0相当于这样的调用?

Mat*_*hen 7

你可以通过调用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();
Run Code Online (Sandbox Code Playgroud)

  • 没有其他方法可以做到吗?与问题中显示的示例相比,这似乎相当麻烦。 (3认同)