且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Python 从一个文本文件复制到另一个文本文件

更新时间:2023-11-27 22:22:28

oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

推荐使用with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:
        f1.writelines(lines)

使用更少的内存:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:
                f1.write(line)