Python freopen () version

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

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?

+8
c ++ c python file file-io
source share
5 answers

sys.stdout is just a 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 intended only to restore the default sys.stdout destination after work (as suggested by Martijn Pieters - you can restore it using sys.__stdout__ or not at all if you don't need it).

+8
source share

If you are using the * 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
source share

You can also 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 opened(filename, "w") as f: with stdout_redirected(f): print "Hello" 
+3
source share

Try the following:

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

Text files are explanatory. Now you can run this code in Sublime Text or any other text editor.

0
source share

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") 
0
source share

All Articles