Copying from one text file to another using Python

前端 未结 8 1801
死守一世寂寞
死守一世寂寞 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) 
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-30 02:20

    with open("list1.txt") as f: doIHaveToCopyTheLine = False '''open output file in write mode''' with open("output.txt", 'w') as f1: '''iterate line by line''' for line in f: if 'tests/file/myword' in line: doIHaveToCopyTheLine = True elif doIHaveToCopyTheLine: f1.write(line)

    f1.close() f.close()

    0 讨论(0)
  • 2020-11-30 02:21
    f=open('list1.txt')  
    f1=open('output.txt','a')
    for x in f.readlines():
        f1.write(x)
    f.close()
    f1.close()
    

    this will work 100% try this once

    0 讨论(0)
  • 2020-11-30 02:28

    Safe and memory-saving:

    with open("out1.txt", "w") as fw, open("in.txt","r") as fr: 
        fw.writelines(l for l in fr if "tests/file/myword" in l)
    

    It doesn't create temporary lists (what readline and [] would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with blocks ensure that the files are closed on exit.

    0 讨论(0)
  • 2020-11-30 02:30
    f = open('list1.txt')
    f1 = open('output.txt', 'a')
    
    # doIHaveToCopyTheLine=False
    
    for line in f.readlines():
        if 'tests/file/myword' in line:
            f1.write(line)
    
    f1.close()
    f.close()
    

    Now Your code will work. Try This one.

    0 讨论(0)
提交回复
热议问题