c++ - freopen() 的 Python 版本

标签 c++ python c file file-io

python 中是否有任何东西可以复制 C 或 C++ 中的 freopen() 的功能?准确地说,我想复制以下功能:

freopen("input.txt","r",stdin);

freopen("output.txt","w",stdout);

然后将相同的(标准)函数用于控制台 I/O 和文件 I/O。有什么想法吗?

最佳答案

sys.stdout 只是 file 对象,因此,您可以将其重新打开到另一个目的地

out = sys.stdout
sys.stdout = open('output.txt', 'w')
// do some work
sys.stdout = out

out 仅用于在工作后将 sys.stdout 目标恢复为默认值(如 Martijn Pieters 所建议 - 您可以使用 sys.__stdout__,或者根本不恢复,如果你不需要的话)。

关于c++ - freopen() 的 Python 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16582194/

相关文章:

c - 我的老师告诉我我的代码是垃圾,为什么?

c++ - cin.ignore() 在程序中不起作用

c++ - 在 g++ 4.4.3 上得到负 NaN,这是标准吗?

c++ - 在异常情况下将临时对象绑定(bind)到非常量引用

python - 使用 gevent 进行行编辑的非阻塞 raw_input

python - 'AxesSubplot' 对象没有属性 'get_axis_bgcolor'

python - 如何在 cPanel 上部署 FastAPI 应用程序?

c - 对于相同的值,double 中的字节散列是否始终相同?

c++ - 我应该如何在 C++ 的类方法中正确使用 __attribute__ ((format (printf, x, y)))?

c - 为什么我的 C 程序没有编译?