Python Script : Delete or Keep only those lines contain a word

Hello friends,

Very often we need to delete all the lines from a text file that have some word. Or quite the opposite, we need to retain only those line and delete all other lines. Here is how:

Keep lines have some words. 

----------------------------------------------------------------------------------

my_words = ['BAKDATA', 'zcat', 'poup']

with open('inputfile.txt') as oldfile, open('outputfile.txt', 'w') as newfile:
    for line in oldfile:
        if any(word in line for word in my_words):
            newfile.write(line)


-------------------------------------------------------------------------------- 
1. This will delete all lines that do not contains words 'BAKDATA', 'zcat', 'poup' and write the result in new file outputfile.txt. Obeviously, inputfile.txt is the input file. If you do not want to specify path, put file and script in same folder.


Delete lines have some words. 

----------------------------------------------------------------------------------

my_words = ['BAKDATA', 'zcat', 'poup']

with open('inputfile.txt') as oldfile, open('outputfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(word in line for word in my_words):
            newfile.write(line)


-------------------------------------------------------------------------------- 
1. This will delete all lines that contains words 'BAKDATA', 'zcat', 'poup' and write the result in new file outputfile.txt. Obeviously, inputfile.txt is the input file. If you do not want to specify path, put file and script in same folder.



Comments