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.