当前位置:  开发笔记 > 编程语言 > 正文

如何将输出写入文件python

如何解决《如何将输出写入文件python》经验,为你挑选了1个好方法。

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

所有模式都在文档中解释



1> Padraic Cunn..:

你需要打开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))

所有模式都在文档中解释

推荐阅读
勤奋的瞌睡猪_715
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有