12

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?

Quixotic
  • 2,424
  • 7
  • 36
  • 58
  • related: [Redirect stdout to a file in Python?](http://stackoverflow.com/q/4675728/4279) – jfs Dec 28 '15 at 23:46

5 Answers5

10

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).

ForEveR
  • 55,233
  • 2
  • 119
  • 133
8

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.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
6

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"
Marcus
  • 6,701
  • 4
  • 19
  • 28
  • As specified in POSIX, [`dup2` will close `newfd` if it is already open](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup.html). In fact, it's better not to close `newfd` explicitly first, since `dup2` guarantees that the close-and-reuse happens atomically. – 200_success Dec 10 '20 at 06:07
4

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"
200_success
  • 7,286
  • 1
  • 43
  • 74
root
  • 76,608
  • 25
  • 108
  • 120
0

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")
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33