3

I'm a beginner in python and I could use some help. Thank you very much. I'm confused about how to actually delete a line where you choose the line by input-ing the info.

in my file:

PSP0101
PCT0101
PYT0101

How do I delete PSP0101 where I can input PSP0101 and it will disappear from the file?

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
S.Iskandr
  • 57
  • 1
  • 2
  • 9
  • Possible duplicate of [Deleting a specific line in a file (python)](http://stackoverflow.com/questions/4710067/deleting-a-specific-line-in-a-file-python) – Juan T Apr 17 '17 at 16:15

1 Answers1

1

You can use input() and then open text file in r+ mode:

with open('test.txt', 'r+') as f:
    t = f.read()
    to_delete = input('What should we delete? : ').strip()   # input PSP0101
    f.seek(0)
    for line in t.split('\n'):
        if line != to_delete:
            f.write(line + '\n')
    f.truncate()

You can check that this has been performed using a text editor, or python:

with open('test.txt') as f:
    print(f.read())

Output:

PCT0101
PYT0101
TrakJohnson
  • 1,755
  • 2
  • 18
  • 31