writing output to file

Stephen D Evans stevee at recombinant.demon.co.uk
Thu Jul 11 16:35:26 EDT 2002


Two simple changes (as per Alex Martelli's alternative suggestion):

1) You can open a file for writing.

2) Redirect your print statement to the resulting file object using the
print>>_file modifier, where _file is the file object that print writes
to. Without the modifier print writes to sys.stdout

3) The third change is to tweak the code for Python 2.2 (I tested this
with 2.2.1). There is no out_stream.close() - Python does this
automatically for the lazy and unsuspecting.


#!/usr/bin/env python
out_stream = file('test.txt', 'w')
for line in file('/etc/passwd'):
    if line.lstrip()[0] == '#':
        continue
    temp = line.split(':')
    if int(temp[2]) > 100 :
        print>>out_stream, "%10s %30s" % (temp[0], temp[4])
#


Stephen D Evans


"Allan Wermuth" <alw at gate2.dda.dk> wrote in message
news:agklgl$rvu$1 at news.net.uni-c.dk...
> 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.
>
> /Allan Wermuth








More information about the Python-list mailing list