Newby: how to transform text into lines of text

Scott David Daniels Scott.Daniels at Acm.Org
Sun Jan 25 19:57:27 EST 2009


John Machin wrote:
> On 26/01/2009 10:34 AM, Tim Chase wrote:
> 
>> I believe that using the formulaic "for line in file(FILENAME)" 
>> iteration guarantees that each "line" will have at most only one '\n' 
>> and it will be at the end (again, a malformed text-file with no 
>> terminal '\n' may cause it to be absent from the last line)
> 
> It seems that you are right -- not that I can find such a guarantee 
> written anywhere. I had armchair-philosophised that writing 
> "foo\n\r\nbar\r\n" to a file in binary mode and reading it on Windows in 
> text mode would be strict and report the first line as "foo\n\n"; I was 
> wrong.

Here's how I'd do it:
     with open('deheap/deheap.py', 'rU') as source:
         for line in source:
             print line.rstrip()  # Avoid trailing spaces as well.

This should handle \n, \r\n, and \n\r lines.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list