且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从文件中删除特定字符串?

更新时间:2023-11-02 23:44:58

readlines 方法返回 的列表,而不是单词,因此您的代码仅在您的一个单词单独位于一行时才有效.

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)