The fundamentals...

Alex Martelli aleaxit at yahoo.com
Thu Jan 25 06:05:37 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.

Not bad!  It IS simple.  It can be changed in various
ways, but it's debatable whether this increases 'elegance'.

You can use string objects' built-in methods instead of
the string module (if you don't have Python 2 yet, get
it -- don't suffer with the limitations of 1.5.2....!-).
You can use normal / slashes rather than repeated backwards
\\ ones.  You need not provide the explicit 'r' when you
are opening a file for reading.  And you need not name
all intermediate values.  So, specifically:

> import string
> test = open('\\Windows\\Desktop\\test.txt', 'r')
> boo = test.read()
> boo = string.split(boo , ". ")
> boo = string.join(boo , "\n")
>
> outfile = open('\\Windows\\Desktop\\out.txt', 'w')
> outfile.write(boo)
> outfile.close()

can become, for example:

data = open('/Windows/Desktop/test.txt').read()
data = '\n'.join(data.split('. '))
open('/Windows/Desktop/out.txt','w').write(data)

or various other combinations yet of named and
unnamed temporary results -- all the way down to
one *rather goofy* single expression:

open('/Windows/Desktop/out.txt','w').write(
    '\n'.join(open('/Windows/Desktop/test.txt')
        .read().split('. '))))

but of course that would be VERY inelegant,
not very readable, fragile, and complicated
to no good purpose!

Deciding what to split out and how to name it,
and what to keep 'joined', is a matter of taste
and style.  Splitting out 'outfile' for example
has the advantage of allowing an explicit close,
not strictly necessary today in CPython but
still a GOOD idea (explicit is better than
implicit).  But one can also end up splitting
things a little bit too much -- particularly when
the names for the intermediate results are not
well chosen (and 'boo' isn't:-), this adds no
real clarity in my personal (& humble) opinion.

"Moderation in all things" is one viable guideline
on such issues of taste and style, I think.


Alex






More information about the Python-list mailing list