The fundamentals...

Quinn Dunkan quinn at barf.ugcs.caltech.edu
Thu Jan 25 01:54:22 EST 2001


On Thu, 25 Jan 2001 00:10:30 GMT, Tim Hochberg <tim.hochberg at ieee.org> wrote:
>"Mike Read" <mread at cableinet.co.uk> wrote in message
>news:F8Jb6.30683$pp2.2619941 at news3.cableinet.net...
>> Newbie first script alert!  No problem - it does what I intended (which
>> probably says more about Python than me...), but I just wanted to start
>> off on the right foot - is it as elegant as it could be?  If it's not
>blindingly
>> obvious, I was separating fields around a period delimiter.
>
>Hi Mike,
>
>There are a couple of things you can do to make it more concise. First, you
>can use replace rather than split and join. Second, you can use string
>methods instead of the functions from the module string. With these two
>changes, it becomes:
>
>infile = open('\\Windows\\Desktop\\test.txt', 'r')
>outfile = open('\\Windows\\Desktop\\out.txt', 'w')
>outfile.write(infile.read().replace(". ", "\n"))
>infile.close()
>outfile.close()

I don't know about windows-land, but at least in unix-land, it would be more
elegant and useful to read from stdin and write to stdout:

import sys
sys.stdout.write(sys.stdin.read().replace('. ', '\n'))

Of course, in unix-land one might be more likely to write

sed -e 's/\. /\
/g'

... which may be enough to make one despise unix-land for the bizarre quoting
rules of the standard shells.



More information about the Python-list mailing list