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 just a certain part of the text? E.g. only copy lines when it has "tests/file/myword" in it?
current code:
#!/usr/bin/env python f = open('list1.txt') f1 = open('output.txt', 'a') doIHaveToCopyTheLine=False for line in f.readlines(): if 'tests/file/myword' in line: doIHaveToCopyTheLine=True if doIHaveToCopyTheLine: f1.write(line) f1.close() f.close()
Right-click and pick Copy, or press Ctrl + C . Navigate to another folder, where you want to put the copy of the file. Click the menu button and pick Paste to finish copying the file, or press Ctrl + V . There will now be a copy of the file in the original folder and the other folder.
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 python with open('output.txt', 'a') as f1: for line in open('list1.txt'): if 'tests/file/myword' in line: f1.write(line)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With