File I / O in the Python 3 C API

The C API in Python 3.0 has changed (deprecated) many functions for file objects.

Before, in 2.X, you can use

PyObject* PyFile_FromString(char *filename, char *mode) 

to create a Python file object, for example:

 PyObject *myFile = PyFile_FromString("test.txt", "r"); 

... but such a function no longer exists in Python 3.0. What would be the equivalent of Python 3.0 for such a call?

+4
source share
2 answers

You can do this the old (new?) Way by simply calling the io module.

This code works, but error checking fails. See Documents for an explanation.

 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(); 
+5
source

This page claims the API:

 PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd); 

Not sure if this means that Python cannot open the file from the file name, but this should be trivial for itself, in C.

+3
source

All Articles