Copying from one text file to another using Python

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

    If all of that did not work try this.

    with open("hello.txt") as f:
    with open("copy.txt", "w") as f1:
        for line in f:
            f1.write(line)
    
    0 讨论(0)
  • 2020-11-30 02:34

    Just a slightly cleaned up way of doing this. This is no more or less performant than ATOzTOA's answer, but there's no reason to do two separate with statements.

    with open(path_1, 'a') as file_1, open(path_2, 'r') as file_2:
        for line in file_2:
            if 'tests/file/myword' in line:
                file_1.write(line)
    
    0 讨论(0)
提交回复
热议问题