[Tutor] Input from and output to a file

Kent Johnson kent37 at tds.net
Wed Feb 7 17:12:04 CET 2007


govind goyal wrote:
> hi,
>  
> 1) I want to read data not from <STDIN> but from a file which is in 
> specified directory.
> 2) I want to redirect my output(which is by default STDOUT) to a file.
>  
> Can anybody suggest these queries?

One way to redirect stdin and stdout is just to do it on the commandline:
python myscript.py < myinput.txt > myoutput.txt

It is easy to read and write files in Python:
f = open('myinput.txt')
data = f.read()
f.close()

gets the contents of myinput.txt into data

f = open('myoutput.txt', 'w')
f.write(data)
f.close()

writes the contents of data to myoutput.txt.

There are many variations on this, any good tutorial will cover file I/O.

It is also possible to directly assign to sys.stdin and sys.stdout but 
I'm not sure that is the best solution for you...

Kent



More information about the Tutor mailing list