Question

I have text file like this:

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

I want to delete line that starts with i.e. test:Player, I already made this, but I don't know how to delete that line? Here's my code so far:

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?

Thanks in advance! :)

Was it helpful?

Solution

# 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()

And don't forget to open the file as readable and writable (r+ instead of r).

To make writes reliable put all operations on file into context manager:

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))

OTHER TIPS

    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()

Hope this helps. Modify according to your requirements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top