gpt4 book ai didi

python - Python 3 C API 中的文件 I/O

转载 作者:太空狗 更新时间:2023-10-29 21:33:07 25 4
gpt4 key购买 nike

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();

关于python - Python 3 C API 中的文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/898136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com