Newbie question: Any way to improve this code?
Duncan Smith
buzzard at urubu.freeserve.co.uk
Sat Dec 6 10:08:19 EST 2003
"Bengt Richter" <bokr at oz.net> wrote in message
news:bqrf08$pke$0 at 216.39.172.122...
> On Sat, 6 Dec 2003 00:06:16 -0000, "Duncan Smith"
<buzzard at urubu.freeserve.co.uk> wrote:
> [...]
> >
> >Or you could replace the whole thing with,
> >
> >try:
> > f = open("firmas.txt",'r')
> > texto = f.read()
> > frases = texto.split('\n')[:-1]
>
> If you split on something, you don't have to eliminate it,
> but you may split off a trailing null string, to satisfy the
> logic that you should be able to join the list with the splitter and
> get back your original. Splitlines does what you want:
>
> >>> 'abc\ndef\n'.split('\n')
> ['abc', 'def', '']
> >>> 'abc\ndef\n'.splitlines()
> ['abc', 'def']
>
> >>> 'abc\ndef\n'.split('\n')
> ['abc', 'def', '']
> >>> '\n'.join('abc\ndef\n'.split('\n'))
> 'abc\ndef\n'
>
> But the result of splitlines gives you the same last line whether it ends
with \n or not,
> so you can't guarantee reconstruction:
>
> >>> '\n'.join('abc\ndef\n'.splitlines())
> 'abc\ndef'
>
> More:
> >>> 'abc\ndef\n'.splitlines()
> ['abc', 'def']
> >>> 'abc\ndef'.splitlines()
> ['abc', 'def']
> >>> 'abc\ndef\n\n'.splitlines()
> ['abc', 'def', '']
> >>> '\n'.splitlines()
> ['']
> >>> ''.splitlines()
> []
> >>> 'a'.splitlines()
> ['a']
>
> >finally:
> > f.close()
> >
> I think you forgot (oh, just realized the explanation for my
amazement--you're not the other Duncan ;-)
> (maybe you didn't forget) that if the open doesn't succeed in the above,
> f will not be (re)bound, so f.close() will be problematical either way.
>
[snip]
Yes, the other Duncan wouldn't have been so sloppy :-). Off to check
whether I've done this in any of my 'real' code. And it was the
frases = texto.split('\n')[:-1]
that I was a bit unhappy about (once I'd posted). I feel a bit like a
certain cartoon character, doh. Cheers Bengt.
Duncan
More information about the Python-list
mailing list