Newbie question: Any way to improve this code?
Bengt Richter
bokr at oz.net
Fri Dec 5 21:30:32 EST 2003
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.
I guess you could fix it (untested) by
try:
f = file("firmas.txt")
try:
frases = f.read().splitlines()
finally:
f.close()
except Exception, e:
print '%s: %s' %( e.__class__.__name__, e)
Regards,
Bengt Richter
More information about the Python-list
mailing list