What is the best way to handle a missing newline in the following case
Paul Rudin
paul.nospam at rudin.co.uk
Fri Nov 5 11:47:10 EDT 2010
"danmcleran at yahoo.com" <danmcleran at yahoo.com> writes:
>> The problem is when I get to the last line. When the program sees '\n'
>> after the 9, everything works fine. However, when there isn't a '\n',
>> the program doesn't process the last line.
>>
>> What would be the best approach to handle the case of the possible
>> missing '\n' at the end of the file?
>
> use readines to read all lines into a list and then iterate thru the
> list:
>
> f = open(r'c:\test.txt', 'rb')
> print f.readlines()
>
>>>
> ['1\r\n', '3\r\n', '5\r\n', '7\r\n', '3\r\n', '9']
There's no real point in contructing a list. Just do
with open(r'c:\test.txt') as f:
for l in f:
print int(l)
As long as you just have digits and whitespace then that's fine - int()
will do as you want.
More information about the Python-list
mailing list