writing output to file

Hans Nowak wurmy at earthlink.net
Thu Jul 11 18:18:09 EDT 2002


Allan Wermuth wrote:

> Inspired by an existing Perl script, I wrote this chunk of code, but instead
> of
> writing the result to the screen, I would like to write output to a another
> file.
> 
> #!/usr/bin/python
> for line in open('/etc/passwd').readlines() :
>    if line.strip()[0] == '#': continue
> 
>  temp = line.split(':')
>   if int(temp[2]) > 100 :
>      print "%10s %30s" % (temp[0], temp[4])
> 
> How can I do that?
> It's possibly quite simple, in Perl it is ;-) , but I am trying to learn
> Python, so
> I would appreciate if someone would help me out.

Redirect sys.stdout:

oldstdout = sys.stdout
sys.stdout = open("some file", "w") # or any file(-like) object

# your code here; print statements should be redirected

# clean up
sys.stdout = oldstdout

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/




More information about the Python-list mailing list