Dave
Dave

Reputation: 883

Extra newline output when using print() in Python

I am brand new to Python. I am reading text from a file & replacing a word. I simply want to output the same two lines, with the word replacement, where the first line ends with a newline.

ADAMS, Ernie, 166 Winterstreamrose Way
NEWLINE, None, 1 Nomorenewlines Street

My test code is:

# readFileLines.py  --- testing file line reading, replacing text & dealing with newlines

with open("line.txt") as f:
    for line in f:
        for word in line.split():
            if word == 'Way':
                line = line.replace("Way", "Street")
        print(line)

Output:

ADAMS, Ernie, 166 Winterstreamrose Street

NEWLINE, None, 1 Nomorenewlines Street

Why do I get an extra newline between the output lines? I note, that like in line.txt, there is no newline after the second line of output.

Any suggestions appreciated.

Upvotes: 0

Views: 1694

Answers (2)

Keith
Keith

Reputation: 43054

The print function adds the extra newline. It is actaully a basic formatter. If you want to emit to stdout the same as you read in you can use sys.stdout.write().

this is more efficient.


with open("line.txt") as f:
    for line in f:
       if "Way" in line:
            line = line.replace("Way", "Street")
       sys.stdout.write(line)

Upvotes: 0

alvas
alvas

Reputation: 122260

When reading file with this idiom:

with open("line.txt") as f:
    for line in f:

The line comes with a \n character at the end.

Try this:

with open("line.txt") as f:
    for line in f:
        line = line.strip()  # Removes the "\n" character
        for word in line.split():
            if word == 'Way':
                line = line.replace("Way", "Street")
        print(line, end="\n") # Puts back the "\n" character.

Or you can use print(line, end=""). By default, print() ends with a \n char, you can specify the the end="" to be to avoid the extra newline with the line isn't striped when reading, i.e.

with open("line.txt") as f:
    for line in f:
        for word in line.split():
            if word == 'Way':
                line = line.replace("Way", "Street")
        print(line, end="")

Upvotes: 2

Related Questions