How to delete specific strings from a file?

The readlines method returns a list of lines, not words, so your code would only work where one of your words is on a line by itself.

Since files are iterators over lines this can be done much easier:

infile = "messy_data_file.txt"
outfile = "cleaned_file.txt"

delete_list = ["word_1", "word_2", "word_n"]
with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        for word in delete_list:
            line = line.replace(word, "")
        fout.write(line)

Leave a Comment