文件I / O是Python 3的C API中
-
23-08-2019 - |
题
在Python 3.0的C API已改变(废弃)的许多文件对象的功能。
在,在2.X,你可以使用
PyObject* PyFile_FromString(char *filename, char *mode)
以创建一个Python文件对象,e.g:
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。
不隶属于 StackOverflow