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.
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.
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.
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)
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