Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying from one text file to another using Python

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() 
like image 625
DevCon Avatar asked Mar 11 '13 16:03

DevCon


People also ask

How do you copy one file to another?

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.


2 Answers

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)  
like image 114
ATOzTOA Avatar answered Oct 17 '22 19:10

ATOzTOA


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) 
like image 26
tdelaney Avatar answered Oct 17 '22 21:10

tdelaney