How to delete specific strings from a file?

后端 未结 5 2057
花落未央
花落未央 2020-12-02 01:22

I have a data file (unstructured, messy file) from which I have to scrub specific list of strings (delete strings).

Here is what I am doing but with no result:

5条回答
  •  孤城傲影
    2020-12-02 01:49

    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)
    

提交回复
热议问题