1

so I have the file: data2.txt

Lollypop,
Lolly pop,
ooh 
lolly,
lolly, lolly;
lollypop, lollypop,
ooh lolly, lolly, lolly,
lollypop!
ba dum dum dum ...

LOL :-)

i need to loop through each line of data2.txt printing only lines that contain the string 'lol' and print the output to a newfile

with open("data3.txt") as g:
    with open("data2.txt") as lfp:
        for lin in lfp:
            if 'lol' in lin:
                g.write(str(lin))
            elif 'LOL' in lin:
                g.write(str(lin))
            elif 'Lol' in lin:
                g.write(str(lin))

But I keep getting error:

    g.write(str(lin))
io.UnsupportedOperation: not writable

2 Answers 2

5

You need to open with w for writing:

with open("data3.txt","w") as g:
    with open("data2.txt") as lfp:

You can also simplify to:

with open("data3.txt", "w") as g, open("data2.txt") as lfp:
        for lin in lfp:
            if 'lol' in lin.lower():
                g.write(lin)

Or use writelines:

with open("data3.txt", "w") as g, open("data2.txt") as lfp:
        g.writelines(line for line in lfp if "lol" in line.lower())

line is already a string so you don't need to call str on it, using "lol" in line.lower() will match all you cases.

If you were explicitly looking for "lol", "Lol", "LOL", any would be a nicer approach.

with open("data3.txt", "w") as g, open("data2.txt") as lfp:
    poss = ("lol", "Lol", "LOL")
    g.writelines(line for line in lfp 
                    if any(s in line for s in poss))

All the modes are explained in the docs

Sign up to request clarification or add additional context in comments.

2 Comments

didn't know you can open two files on one line, nice answer!
@martijnn2008, yep, you can open as many as you want, you can so it with any objects the support the use of a context manager
0

The problem is in the line with open("data3.txt") as g:

You didn't provide open with a mode, and the default is r which is only for reading. Use with open("data3.txt", 'w') as g: if you want to replace the file if it is already exists or with open("data3.txt", 'a') as g: if you want to append to the file if it is already exists.

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.