Redirecting stdin to a file

MRAB python at mrabarnett.plus.com
Fri Dec 4 18:59:17 EST 2009


candide wrote:
> How do I redirect stdin to a text file ? In C, this can be done with
> the freopen() standard function, for instance
> 
> FILE *foo = freopen("in.txt", "r", stdin);
> 
> 
> redirects stdin to the in.txt text file. Does anyone know a freopen()
> Python equivalent ?
> 
> Notice that I'm not referring to shell redirection as the following 
> command line shows :
> 
> $ python myCode.py < in.txt
> 
> I need to hardcode the redirection inside the python source file.

The standard input is sys.stdin and the standard output is sys.stdout.

sys.stdin.close()
sys.stdin = open("in.txt", "r")



More information about the Python-list mailing list