writing output to file

Alex Martelli aleax at aleax.it
Thu Jul 11 16:01:32 EDT 2002


Allan Wermuth wrote:
        ...
> 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?

My personal suggestion:

flout = open('/tmp/otherfile', 'w')
for line in open('/etc/passwd').readlines() :
    if line.strip()[0] == '#': continue
 
    temp = line.split(':')
    if int(temp[2]) > 100:
        flout.write("%10s %30s\n" % (temp[0], temp[4]))
flout.close()

An alternative:

flout = open('/tmp/otherfile', 'w')
for line in open('/etc/passwd').readlines() :
    if line.strip()[0] == '#': continue
 
    temp = line.split(':')
    if int(temp[2]) > 100:
        print >> flout, "%10s %30s" % (temp[0], temp[4])
flout.close()


As you see, the difference boils down to using a variant
of the print statement (with the clause  >> flout ,  to
direct output elsewhere) versus using the write method
of the file-object flout (which, differently from print,
just takes whatever string you give it and puts it out
to the file without alterations).

My personal opinion is that print is good for simple
quick & dirty output for debugging purposes, while using
formatting operations to prepare strings and then the
write method of file objects to emit them is the best
way to go for "production" code.  But, if you disagree,
the  >> flout ,  clause in the print statement lets you
use the print statement to write to a file, too.


Alex





More information about the Python-list mailing list