Sin*_*oda 1 python file input output
所以我有文件:data2.txt
Lollypop,
Lolly pop,
ooh
lolly,
lolly, lolly;
lollypop, lollypop,
ooh lolly, lolly, lolly,
lollypop!
ba dum dum dum ...
LOL :-)
Run Code Online (Sandbox Code Playgroud)
我需要循环遍历每行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))
Run Code Online (Sandbox Code Playgroud)
但我一直在收到错误:
g.write(str(lin))
io.UnsupportedOperation: not writable
Run Code Online (Sandbox Code Playgroud)
你需要打开w
写作:
with open("data3.txt","w") as g:
with open("data2.txt") as lfp:
Run Code Online (Sandbox Code Playgroud)
您还可以简化为:
with open("data3.txt", "w") as g, open("data2.txt") as lfp:
for lin in lfp:
if 'lol' in lin.lower():
g.write(lin)
Run Code Online (Sandbox Code Playgroud)
或者使用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())
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
所有模式都在文档中解释