Remove lines that contain certain string

后端 未结 9 1363
予麋鹿
予麋鹿 2020-11-30 01:00

I\'m trying to read a text from a text file, read lines, delete lines that contain specific string (in this case \'bad\' and \'naughty\'). The code I wrote goes like this:

9条回答
  •  鱼传尺愫
    2020-11-30 01:35

    You can make your code simpler and more readable like this

    bad_words = ['bad', 'naughty']
    
    with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
        for line in oldfile:
            if not any(bad_word in line for bad_word in bad_words):
                newfile.write(line)
    

    using a Context Manager and any.

提交回复
热议问题