Python: filter strings from a text file containing a specific word

In Python, I want to write a program that filters lines from my text file that contain the word "apple" and write these lines to a new text file. What I tried just writes the word "apple" into my new text file, while I need whole lines. I am new to Python, so kindly answer my question as I really need it.

+8
python filter line
source share
4 answers

Usage can get all strings containing "apple" using list comprehension:

[ line for line in open('textfile') if 'apple' in line] 

So - also in one line of code - you can create a new text file:

 open('newfile','w').writelines([ line for line in open('textfile') if 'apple' in line]) 

And eyquem is right: it is definitely faster to save it as an iterator and write

 open('newfile','w').writelines(line for line in open('textfile') if 'apple' in line) 
+16
source share
 from itertools import ifilter with open('source.txt','rb') as f,open('new.txt','wb') as g: g.writelines( ifilter(lambda line: 'apple' in line, f)) 
+8
source share

Using generators is efficient and fast memory

 def apple_finder(file): for line in file: if 'apple' in line: yield line source = open('forest','rb') apples = apple_finder(source) 

I like easy solutions without brain damage for reading :-)

+5
source share

if "apple" in line: should work.

+1
source share

All Articles