Python 3 C API中的文件I/O [英] File I/O in the Python 3 C API

查看:65
本文介绍了Python 3 C API中的文件I/O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.0中的C API已更改(不建议使用)文件对象的许多功能.

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

之前,在2.X版本中,您可以使用

Before, in 2.X, you could use

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

创建一个Python文件对象,例如:

to create a Python file object, e.g:

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

...但是此类功能在Python 3.0中不再存在. 等同于此类调用的Python 3.0是什么?

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

推荐答案

您可以通过调用io模块以旧的(新的?)方式进行操作.

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

这篇关于Python 3 C API中的文件I/O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆