stdio EOF ?
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Aug 13 07:46:53 EDT 2002
Paul Rubin <phr-n2002b at NOSPAMnightsong.com> wrote in
news:7xbs87dmfs.fsf at ruckus.brouhaha.com:
> Duncan Booth <duncan at NOSPAMrcp.co.uk> writes:
>> If you don't like having to strip all the newlines from each line,
>> then an alternative is to write a generator to do it for you:
>
>> from __future__ import generators
>> import sys
>>
>> def filelines(f):
>> while 1:
>> line = f.readline()
>> if not line: break
>> yield line[:-1]
>>
>> for line in filelines(sys.stdin):
>> print "**",`line`,"**"
>
> Oops! This chops the last character if the last line of the file
> doesn't end with newline.
>
Any non-trivial code has bugs[1] (I managed a 4 byte program[2] once, with
a bug). If there is a chance that there is no newline at the end of the
file then use:
yield line.endswith('\n') and line[:-1] or line
or if you don't care about trailing spaces then a cleaner option may be:
yield line.rstrip()
[1] At least any I write does.
[2] That was the second shortest (useful) program I ever wrote.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list