Payam_2021
Payam_2021

Reputation: 19

delete a specific line in txt file if it consist a special word

i ask for a input, if that input was in a line of my txt file, delete just that line

w = input("Enter STnumber: ")
with open("student.txt ", "r") as f:
     lines = f.readlines()
     with open('student.txt','w') as f:
         for line in lines:
             if w in line :
                 # (i cant undrstand here)

these will clear all of my txt file actually its a name , lastname and a number in the txt file, like this jon sina 1234

if w = 1234, delete just the line with a number 1234

Upvotes: -1

Views: 58

Answers (1)

Adon Bilivit
Adon Bilivit

Reputation: 26825

If you want to remove lines from a text file that contain a certain pattern then you could do this:

with open('foo.txt', 'r+') as foo:
    lines = foo.readlines()
    foo.seek(0)
    for line in lines:
        if not 'Pattern' in line:
            foo.write(line)
    foo.truncate()

Upvotes: 2

Related Questions