12
votes

Is there anything in python that can replicate the functionality of freopen() in C or C++? To be precise, I want to replicate the functionality of:

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

and

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

And then use the same (standard) functions for console I/O for file I/O. Any ideas?

5

5 Answers

11
votes

sys.stdout is simply file object, so, you can reopen it to another destination

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

out is only for recovering sys.stdout destination to default after work (as suggested Martijn Pieters - you can recover it by using sys.__stdout__, or not recover at all, if you don't need it).

7
votes

Try this:

import sys
sys.stdin = open('input.txt', 'r') 
sys.stdout = open('output.txt', 'w')

Text files are self explanatory. You can now run this code on Sublime Text or any other text editor.

6
votes

If you're working on *nix platform, you can write your own freopen.

def freopen(f,option,stream):
    import os
    oldf = open(f,option)
    oldfd = oldf.fileno()
    newfd = stream.fileno()
    os.close(newfd)
    os.dup2(oldfd, newfd)

import sys
freopen("hello","w",sys.stdout)

print "world"
4
votes

You may also want to look at the contextmanager decorator in contextlib for temporary redirection:

from contextlib import contextmanager 
import sys 

@contextmanager
def stdout_redirected(new_stdout):
    save_stdout = sys.stdout
    sys.stdout  = new_stdout
    try:
        yield
    finally:
        sys.stdout = save_stdout

Example:

 with open(filename, "w") as f:
     with stdout_redirected(f):
         print "Hello"
0
votes

This should help:

import sys

def freopen(filename, mode):
    if mode == "r":
        sys.stdin = open(filename, mode)

    elif mode == "w":
        sys.stdout = open(filename, mode)

# ---- MAIN ----

freopen("input.txt", "r")
freopen("output.txt", "w")