繁体   English   中英

如何将输出写入文件python

[英]how to write the output to a file python

所以我有文件: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)

或使用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" 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))

所有模式均在文档中进行了说明

问题出在with open("data3.txt") as g:的一行中with open("data3.txt") as g:

您未提供open模式,默认值为r ,仅用于读取。 使用with open("data3.txt", 'w') as g:如果要替换该文件(如果已存在),或者with open("data3.txt", 'a') as g:如果要如果文件已经存在,则追加到该文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM