所以我有文件:data2.txt
Lollypop,
Lolly pop,
ooh
lolly,
lolly, lolly;
lollypop, lollypop,
ooh lolly, lolly, lolly,
lollypop!
ba dum dum dum ...
LOL :-)
我需要循环遍历data2.txt的每一行,只打印包含字符串< lol'并将输出打印到新文件
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))
但我一直收到错误:
g.write(str(lin))
io.UnsupportedOperation: not writable
答案 0 :(得分:5)
您需要打开w
进行撰写:
with open("data3.txt","w") as g:
with open("data2.txt") as lfp:
您还可以简化为:
with open("data3.txt", "w") as g, open("data2.txt") as lfp:
for lin in lfp:
if 'lol' in lin.lower():
g.write(lin)
或使用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
已经是一个字符串,因此您无需在其上调用str
,使用"lol" in line.lower()
将匹配所有案例。
如果您明确地寻找"lol", "Lol", "LOL"
,那么any
将是一种更好的方法。
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))
所有模式都在docs
中说明答案 1 :(得分:0)
问题在于行with open("data3.txt") as g:
您未向open
提供模式,默认为r
,仅供阅读。如果要替换文件(如果文件已存在),请使用with open("data3.txt", 'w') as g:
;如果要存在,请使用with open("data3.txt", 'a') as g:
{。{}}