[Tutor] file I/O
Roman Suzi
rnd@onego.ru
Thu, 12 Jul 2001 08:32:13 +0400 (MSD)
On Wed, 11 Jul 2001, Michael P. Reilly wrote:
>Massey, Craig wrote
>>
>
>But readline simplifies this as I said above. Just using
>f.readline()[:-1] is good enough.
No, it is not. Last line of a file could contain no
"\n". Why not to write chomp?
def chomp(s):
if s[-1:] == "\n":
return s[:-1]
else:
return s
Or, another way:
>>> def chomp1(s):
... return s[-1:] != "\n" and s or s[:-1]
...
>>> chomp1("")
''
>>> chomp1("1")
'1'
>>> chomp1("12")
'12'
>>> chomp1("12\n")
'12'
>>> chomp1("12\n\n")
'12\012'
>
Sincerely yours, Roman Suzi
--
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd@onego.ru _/
_/ Thursday, July 12, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "Misfortune: The kind of fortune that never misses." _/