file print extra spaces

MRAB python at mrabarnett.plus.com
Tue Mar 22 22:05:44 EDT 2011


On 23/03/2011 01:33, 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
>
>
> author_list = {
>
> '829337' : {
>
> 'author_name' : 'Carter, John',
>
> 'count' : 49,
>
> 'c2' : '0.102040816326531',
>
> How can i print the file out without having an extra newline between
> printed lines?
>
> Thanks for the help all.

Each line read from the file still includes its line ending, and
'print' normally prints a newline at the end, which is why you're
getting a blank line.

You could stop the print from printing its newline:

     print(line, end="") # Python 3

or:

     print line, # Python 2

or you could strip the newline off what you're printing:

     print(line.rstrip('\n'))



More information about the Python-list mailing list