-3

I want to delete a specific line in a text file in python. for example, say in my text file I have:

Ben Walsh - 768

James Cook - 659

Jamie Walsh - 4359

Owen Perkins - 699

Dylan Thomas - 1574

Adam Ward - 987

Allen Woodhouse - 599

I want to delete any line that contains the number 699. How do I do this?

I have tried using this to solve it,Deleting a specific line in a file (python) however, using Tkinter I am asking the user to enter the number of the person they want to delete. So the number decides what is deleted because there are other items on the line it does not delete it.

Ben Walsh
  • 19
  • 1
  • 2

2 Answers2

3

First, open the file:

f = open("yourfile.txt","r")

Next, get all your lines from the file:

lines = f.readlines()

Now you can close the file:

f.close()

And reopen it in write mode:

f = open("yourfile.txt","w")

Then, write your lines back, except the line you want to delete.

for line in lines:
  if "699" not in line:
    f.write(line)

At the end, close the file again.

f.close()
lefft
  • 2,065
  • 13
  • 20
0

Very simple:

    with open(file, "r+") as f:
        d = f.readlines()
        posdel = num-1
        for i in range(0,len(d)):
            if i == posdel:
                del d[posdel]
    with open(file, "w") as textobj:
        for n in d:
            textobj.write(n)
Izalion
  • 708
  • 4
  • 11