On 2010-11-05, Paul Rudin <paul.nos...@rudin.co.uk> wrote: > "danmcle...@yahoo.com" <danmcle...@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.
Keep in mind that a file that a text file that doesn't end with a newline isn't strictly legal. You can expect problems, or at least warnings, with other tools with such files. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list