所以我有文件:data2.txt
Lollypop, Lolly pop, ooh lolly, lolly, lolly; lollypop, lollypop, ooh lolly, lolly, lolly, lollypop! ba dum dum dum ... LOL :-)
我需要循环遍历每行data2.txt只打印包含字符串'lol'的行并将输出打印到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))
但我一直在收到错误:
g.write(str(lin)) io.UnsupportedOperation: not writable
Padraic Cunn.. 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))
所有模式都在文档中解释
你需要打开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))
所有模式都在文档中解释