Deleting specific strings from file using Python

I had to delete/replace few words from few text files. Find and Replace feature wouldn’t come handy if there are too many files to edit.

The following python script helps us to replace specific string/phrase from the file with something else.


#filename=prune.py

infile = "file.txt"
outfile = "updated_file.txt"

delete_list = ["phrase1", "phrase2"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
    for word in delete_list:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()

 

0 comments:

Leave a Reply

Your email address will not be published. Required fields are marked *