Reputation: 311
I'm having a problem with how can I write a string in every new line in a text file. Please see attached image:
Above image is the original text file. Now I want to add some text in every newline. Please see attached image:
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
Reputation: 1116
You make several mistakes:
A newline is not the same as an empty line. You look to replace empty lines with your text.
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