0

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.

2 Answers 2

2

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="")
Sign up to request clarification or add additional context in comments.

Comments

0

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)

10 Comments

print already gave a new line after printng the line ADAMS, Ernie, 166 Winterstreamrose Street Right? why again a blank new line
Exactly. So writing it back out without the extra formatting of print won't add extra newlines. Use the newline that's already in the text. There is also no need to split the line.
If the goal is to keep the file exactly the same, except for replacing "Way" with "Street" then you really don't want to try and replace the line endings. That would be an unspecified change.
That implementation will be slower. It has more steps than is required to perform the task that you specify.
@Dave oops, yes, I had one extra space. Fixed it. BTW, both print and sys.stdout use the same C code. The difference is print, by default, appends a newline to the output. The sys.stdout writes whatever you give it, as-is. This code is not faster because of that, but because it doesn't do the extra steps of splitting the line. It does a substring search. In Python, strings are "immutable", and can't be altered in-place. Any string operations, such as split, result in new object allocations and data copies. Which are then immediately discarded, resulting in yet another call to free.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.