所以我有文件: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
请您参考如下方法:
写入需要用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)
或者使用写行:
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,在 line.lower() 中使用 "lol" 将匹配您所有的情况。
如果您要明确查找 "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 中进行了解释
