如何将输出写入python文件
所以我有一个文件:data2.txt如何将输出写入python文件,python,file,input,output,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 :-) 我需要遍历data2.txt的每一行,只打印包含字符串“lol”的行,并将输出打印到一个新文件中 with open("data3.txt") as g: with open("data2.t
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)
或使用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())
行
已经是一个字符串,所以您不需要在它上面调用str
,在行中使用“lol”。lower()
将匹配所有情况
如果您明确地寻找“lol”、“lol”、“lol”
,任何
都是更好的方法
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())
行
已经是一个字符串,所以您不需要在它上面调用str
,在行中使用“lol”。lower()
将匹配所有情况
如果您明确地寻找“lol”、“lol”、“lol”
,任何
都是更好的方法
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))
所有模式都在中进行了解释。问题出现在带有open(“data3.txt”)的
行中,如g:
您没有为
open
提供模式,默认为r
,仅用于阅读。如果您想将文件替换为已存在的文件,请将与open('data3.txt','w')一起用作g:
,如果您想将open('data3.txt','a')与g:一起用作g:问题在于将open('data3.txt')作为g:
您没有为
open
提供模式,默认为r
,仅用于阅读。如果您想替换已经存在的文件,请将与open(“data3.txt”,“w”)一起用作g:
,如果您想附加到已经存在的文件,请将与open(“data3.txt”,“a”)一起用作g:
。不知道您可以在一行中打开两个文件,回答不错@martijnn2008,是的,你可以打开任意多个,你可以使用任何对象。支持使用上下文管理器。我不知道你可以在一行上打开两个文件,回答得很好@martijnn2008,是的,你可以打开任何你想要的东西,你可以用任何支持使用上下文管理器的对象