I am writing the content of “article” to a text file.
Source file:
lol hi
lol hello
lol text
lol test
Python:
for line in all_lines:
if line.startswith('lol '):
mystring = line.replace('lol ', '').lower().rstrip()
article = 'this is my saved file\n' + mystring + '\nthe end'
This is what gets saved to the txt file:
this is my saved file
test
the end
This is what I want saved to the txt file:
this is the saved file
hi
hello
test
text
the end
You are replacing the string each time. You will want to store the results of each
lolline and then add them all tomystring:In the above code, I’ve turned
mystringinto list which is then turned into a string at the end using thejoinmethod. Note that I’ve added a newline (\n) character to each line as you want that character in your output (andrstrip()removes it). Alternatively, you can write:which lets
rstrip()only strip spaces and not all other forms of whitespace.Edit: An alternative approach is to write:
and: