0

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!

4
  • How big is the file? Commented Apr 10, 2019 at 3:25
  • @Selcuk it's just a bytes size. Commented Apr 10, 2019 at 3:27
  • Sorry, I mean, what is the total size of the file? If it is small, you can read whole file into memory (instead of reading it line by line) and then replace the strings "\n\n" with "\nEND\n". Commented Apr 10, 2019 at 3:29
  • @Selcuk it is just a small file sir, how can I do it sir? Commented Apr 10, 2019 at 3:37

1 Answer 1

1

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

Comments

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.