Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File I/O in the Python 3 C API

The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects.

Before, in 2.X, you could use

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

to create a Python file object, e.g:

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

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

like image 476
Vicent Marti Avatar asked May 22 '09 14:05

Vicent Marti


People also ask

What is C API in Python?

The Python/C API allows for compiled pieces of code to be called from Python programs or executed within the CPython interpreter. This process of producing compiled code for use by CPython is generally known as "extending" Python and the compiled pieces of code to be used are known as "extension modules".

What is io Open in Python?

io. open() method opens a file, in the mode specified in the string mode. It returns a new file handle, or, in case of errors, nil plus an error message.

What is io StringIO in Python?

The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.


1 Answers

You can do it the old(new?)-fashioned way, by just calling the io module.

This code works, but it does no error checking. See the docs for 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();
like image 176
Matthew Flaschen Avatar answered Oct 24 '22 07:10

Matthew Flaschen