我有这样的文本文件:
test:Player:232.746860697:76.0:206.635144909
b2:Player2:245.330907228:77.0:207.785677928
b3:Player4:236.52764454:76.0:203.95246227
b45:Player33:240.496564206:77.0:205.574781979
我想删除以test:Player开头的行,我已经这样做了,但我不知道如何删除该行?到目前为止,这是我的代码:
pluginlokacija2 = os.path.realpath("%s/plugins"%os.getcwd())
textfile = open("%s/CreativePoints/Data/plotovi.txt"%pluginlokacija2, 'r')
for line in textfile.readlines():
if line.startswith("%s:%s"%(args[1], sender.getName())):
#delete that line, how?
提前致谢! :)
答案 0 :(得分:1)
# Filter unwanted lines
a = filter(lambda x: not x.startswith("%s:%s"%(args[1], sender.getName())), \
textfile.readlines())
# Write filtered lines to file
textfile.seek(0)
textfile.truncate()
textfile.writelines(list(x.strip() for x in a))
textfile.close()
不要忘记将文件打开为可读写(r+
而不是r
)。
为了使写入可靠,将所有操作存入上下文管理器:
from itertools import ifilterfalse
with open('/home/reserve/Desktop/s.txt', 'r+') as f:
b = ifilterfalse(lambda x: x.startswith("%s:%s"%(args[1],sender.getName())),\
f.readlines())
f.seek(0)
f.truncate()
f.writelines(list(x.strip() for x in b))
答案 1 :(得分:1)
f = open("a.txt","r")
lines = f.readlines()
f.close()
f = open("a.txt","w")
for line in lines:
if not line.startswith('test:Player'):
f.write(line)
print(line)
f.close()
希望这会有所帮助。根据您的要求进行修改。