您可以通过调用 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();