-1

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

Matthias
  • 12,873
  • 6
  • 42
  • 48
Payam_2021
  • 19
  • 5
  • Does your code not work? Are you getting an error, warning, or unexpected behavior? If unexpected, what is supposed to be the output and what are you getting? Please read [How to ask a question](https://stackoverflow.com/help/how-to-ask) – blackbrandt Jul 06 '22 at 11:39
  • 1
    Your code does the exact opposite of your description – Sayse Jul 06 '22 at 11:40
  • that was what i saw in google search – Payam_2021 Jul 06 '22 at 11:48

1 Answers1

2

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()
DarkKnight
  • 19,739
  • 3
  • 6
  • 22