file print extra spaces

MRAB python at mrabarnett.plus.com
Tue Mar 22 22:25:55 EDT 2011


On 23/03/2011 01:54, Thomas L. Shinnick wrote:
> At 08:33 PM 3/22/2011, monkeys paw wrote:
>> When i open a file in python, and then print the
>> contents line by line, the printout has an extra blank
>> line between each printed line (shown below):
>>
>> >>> f=open('authors.py')
>> >>> i=0
>> >>> for line in f:
>> print(line)
>> i=i+1
>> if i > 14:
>> break
>
> Try
> print(line.rstrip())
>
> Your 'line' text value must still have line endings in it. .rstrip()
> will remove trailing whitespace on the right. print() will then do its
> own line ending.
>
> Answer I don't know: why are the line endings still in the text values?
>
[snip]

Because they are in the file.

Iterating over the file yields a line at a time (like file.readline()).
All but the last line will have a line ending; the last line may.

You might want to know what is actually in the file, including whether
the last line has a line ending or not, so you don't always want to
drop it, if present.



More information about the Python-list mailing list