Copying from one text file to another using Python

前端 未结 8 1852
死守一世寂寞
死守一世寂寞 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

    readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.

    #!/usr/bin/env python
    with open('output.txt', 'a') as f1:
        for line in open('list1.txt'):
            if 'tests/file/myword' in line:
                f1.write(line)
    

提交回复
热议问题