Copying from one text file to another using Python Copying from one text file to another using Python python python

Copying from one text file to another using Python


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) 


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 pythonwith open('output.txt', 'a') as f1:    for line in open('list1.txt'):        if 'tests/file/myword' in line:            f1.write(line)


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)