| Store | Cart

writing output to file

From: Stephen D Evans <ste...@recombinant.demon.co.uk>
Thu, 11 Jul 2002 21:35:26 +0100
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

Recent Messages in this Thread
Allan Wermuth Jul 11, 2002 07:25 pm
Ralf Claus Jul 11, 2002 07:17 pm
Mark McEahern Jul 11, 2002 07:27 pm
Alex Martelli Jul 11, 2002 08:01 pm
Allan Wermuth Jul 11, 2002 08:50 pm
Emile van Sebille Jul 12, 2002 12:00 am
Stephen D Evans Jul 11, 2002 08:35 pm
Hans Nowak Jul 11, 2002 10:18 pm
Alex Martelli Jul 12, 2002 09:24 am
Messages in this thread