The fundamentals...

Tim Hochberg tim.hochberg at ieee.org
Wed Jan 24 19:10:30 EST 2001


"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()

Finally, it is common practice to omit the closing of files in many
situations. (Whether it's good practice is an issue for another thread).
This works because the file is automatically closed when the file's
reference count drops to zero(*). So, if the above were appearing in a
function:

def dotToReturn(inpath, outpath):
    infile = open(inpath, 'r')
    outfile = open(outpath, 'w')
    outfile.write(infile.read().replace(". ", "\n"))

dotToReturn('\\Windows\\Desktop\\test.txt', '\\Windows\\Desktop\\out.txt')

the files would be closed at the end of the dotToReturn function. One final
entry for those who crave terseness:

open(outpath, 'w').write(open(inpath, 'r').read().replace(". ", "\n"))

This is a bit too terse for my tastes, but tastes vary...

-tim






(*) One needs to be careful about this if using Jython, formerly Jpython





More information about the Python-list mailing list