Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python version of freopen()

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?

like image 815
Quixotic Avatar asked May 16 '13 08:05

Quixotic


People also ask

What is Freopen?

The freopen() function opens the new file associated with stream with the given mode, which is a character string specifying the type of access requested for the file. You can also use the freopen() function to redirect the standard stream files stdin , stdout , and stderr to files that you specify.

What is Freopen input TXT R Stdin?

freopen("input.txt", "r", stdin); and freopen("output.txt", "w", stdout) are C library function calls that reuse stdin and stdout standard input and standard output stream file pointers as file pointers to the files input.txt and output.txt , respectively.

How do I use Freopen in CPP?

freopen() prototypeThe freopen function first attempts to close the file opened using stream . After the file is closed, it attempts to open the filename specified by the argument filename (if it is not null) in the mode specified by the argument mode . Finally it associates the file with the file stream stream .


1 Answers

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.

like image 86
Kushagra Kukreja Avatar answered Oct 02 '22 16:10

Kushagra Kukreja