Copying from one text file to another using Python

前端 未结 8 1834
死守一世寂寞
死守一世寂寞 2020-11-30 01:56

I would like to copy certain lines of text from one text file to another. In my current script when I search for a string it copies everything afterwards, how can I copy jus

8条回答
  •  粉色の甜心
    2020-11-30 02:15

    The oneliner:

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

    Recommended with 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)
    

    Using less memory:

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

提交回复
热议问题