我有一个包含此类名称列表的txt文件
Name1
Name2
Name3
我想删除" Name2"在其中,如果Name2在列表中。我得到了这段代码:
f = open(list,'r')
if("Name2" in f.read().splitlines()):
lines = f.readlines()
f.close()
f = open(badhumanslist, "w")
for line in lines:
if line != "Name2" + "\n":
f.write(line)
f.close()
问题是这段代码会清空整个文件。我没有看到我的错误,它应该重写所有的行,除了" Name2"
答案 0 :(得分:2)
您已经在第2行读取了整个文件:f.read()
。然后,lines = f.readlines()
返回一个空列表。
def read_all():
with open(filename, "r") as file:
return file.read()
content = read_all()
lines = content.splitlines()
if "Name2\n" in lines:
with open(filename, "w") as file:
for line in lines:
if line != "Name2\n":
file.write(line)