1

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
0

3 Answers 3

5

You are replacing the string each time. You will want to store the results of each lol line and then add them all to mystring:

mystring = []
for line in all_lines:
    if line.startswith('lol '):
        mystring.append(line.replace('lol ', '', 1).lower().rstrip() + '\n')

article = 'this is my saved file\n'+''.join(mystring)+'\nthe end'

In the above code, I've turned mystring into list which is then turned into a string at the end using the join method. Note that I've added a newline (\n) character to each line as you want that character in your output (and rstrip() removes it). Alternatively, you can write:

line.replace('lol ', '', 1).lower().rstrip(' ')

which lets rstrip() only strip spaces and not all other forms of whitespace.


Edit: An alternative approach is to write:

mystring.append(line.replace('lol ', '').lower().rstrip())

and:

article = 'this is my saved file\n'+'\n'.join(mystring)+'\nthe end'
Sign up to request clarification or add additional context in comments.

5 Comments

replace is a little dangerous here; replace('lol ','', 1) would prevent the possibility of an unintentional second replacement.
@SimeonVisser -- I deleted my comment because it was incorrect. But I'm glad you added that alternative. (it's more clear to me anyway).
@mgilson: Why is it incorrect? Each line (except the last) will get a \n using join() and the last line will get it as well from '\nthe end'. Of course, it is not platform-independent code...
@SimeonVisser -- your answer is completely correct. It was my comment which was wrong. (hence my deleting it).
You could do this with one generator: 'this is my saved file\n' + ''.join(line.replace('lol ', '').lower() for line in all_lines if line.startswith('lol ')) + 'the end'
0

... or as a one-liner,

mystring = ''.join(line[4:].lower() for line in all_lines if line.startswith('lol '))

Comments

0

You could take this different approach:

with open('test.txt') as fin, open('out.txt', 'w') as fout:
    fout.write('this is my saved file\n')
    for line in fin:
        if line.startswith('lol '):
            fout.write(line.replace('lol ', '').lower())
    fout.write('the end')

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.