N.Omugs
N.Omugs

Reputation: 311

Python - Write a string in every new line

I'm having a problem with how can I write a string in every new line in a text file. Please see attached image:

enter image description here

Above image is the original text file. Now I want to add some text in every newline. Please see attached image:

enter image description here

Now I added the word "END". How can I do it in python? I tried to use the normal file reading then adding this stuff:

if 'PING' in line:
    new_file.write("END")
elif 'ST' in line:
    new_file.write("END")
etc. .

But I think this way isn't flexible. Do you guys have any ideas on how can I do it? Thank you very much!

Upvotes: 0

Views: 78

Answers (1)

Jytug
Jytug

Reputation: 1116

You make several mistakes:

  1. A newline is not the same as an empty line. You look to replace empty lines with your text.

  2. PING has nothing to do with an empty line.

To achieve what I mentioned in point 1, you can use the following snippet

with open('myfile','rw') as file:
    for line in file:
        if line.isspace():
            file.write("your text")
        else:
            file.write(line)

Upvotes: 1

Related Questions