MishaVacic MishaVacic -3 years ago 222
Python Question

Python line ending ' '

This code

with open('iter.txt') as f:
while True:
line = next(f)
except StopIteration:

Works as expected.
But with


Empty line is inserted.

Iteration is one of Python’s strongest features. At a high level, you might simply view

iteration as a way to process items in a sequence. However, there is so much more that

is possible, such as creating your own iterator objects,

Is there any alternative with os.linesep?

Answer Source

As far as I understood, you want to print a new line symbol (os.linesep) if only your line does not end with it in order to prevent this additional blank line.

It can be solved with a check like this:

import os

with open('iter.txt') as f:
    for line in f:
        # Print with end='' if your line contains a new line
        # Otherwise, print this new line

        linesep = os.linesep
        line_end = '' if linesep in line else linesep

        print(line, end=line_end)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download