删除包含某些字符串的行 [英] Remove lines that contain certain string
本文介绍了删除包含某些字符串的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从文本文件中读取文本,读取行,删除包含特定字符串(在这种情况下为坏"和顽皮")的行. 我写的代码是这样的:
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:
infile = file('./oldfile.txt')
newopen = open('./newfile.txt', 'w')
for line in infile :
if 'bad' in line:
line = line.replace('.' , '')
if 'naughty' in line:
line = line.replace('.', '')
else:
newopen.write(line)
newopen.close()
我这样写,但没有成功.
I wrote like this but it doesn't work out.
重要的是,如果文本内容是这样的:
One thing important is, if the content of the text was like this:
good baby
bad boy
good boy
normal boy
我不希望输出中有空行. 所以不喜欢:
I don't want the output to have empty lines. so not like:
good baby
good boy
normal boy
但是像这样:
good baby
good boy
normal boy
我应该从上面的代码中编辑什么?
What should I edit from my code on the above?
推荐答案
您可以像这样使代码更简单,更易读
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)
使用 Context Manager 和 查看全文