Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter lines from a text file which contain a particular word

I want to write a program which filters the lines from my text file which contain the word "apple" and write those lines into a new text file.

What I have tried just writes the word "apple" in my new text file, whereas I want whole lines.

like image 202
ahmad Avatar asked Mar 09 '11 11:03

ahmad


People also ask

How do you filter a file in Python?

How to Filter and List Files According to Their Names in Python? To filter and list the files according to their names, we need to use “fnmatch. fnmatch()” and “os. listdir()” functions with name filtering regex patterns.

How do you filter text in Python?

filter() method is a very useful method of Python. One or more data values can be filtered from any string or list or dictionary in Python by using filter() method. It filters data based on any particular condition. It stores data when the condition returns true and discard data when returns false.


1 Answers

Use can get all lines containing 'apple' using a list-comprehension:

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

So - also in one code-line - you can create the new textfile:

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

And eyquem is right: it's definitely faster to keep it as an iterator and write

open('newfile','w').writelines(line for line in open('textfile') if 'apple' in line)
like image 174
phynfo Avatar answered Sep 24 '22 07:09

phynfo