我目前拥有的代码可以删除包含一个特定字符串的文本文件中的所有行。这里是:如果行包含几个指定字符串之一,则从文本文件中删除行Python
import os
with open(r"oldfile") as f, open(r"workfile", "w") as working:
for line in f:
if "string1" not in line:
working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")
我的问题是:我怎么能包括其他字符串?换句话说,我想告诉脚本,如果一行包含“string1”或某个其他字符串“string2”,则删除该行。我知道我可以重复上面为每个这样的字符串提供的代码,但我确定有一些更简短更有效的方式来编写它。
非常感谢提前!
这可能帮助:https://stackoverflow.com/ question/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python – yinnonsanders