-1

My text has student data in the form of 1234:zakasi:2:1:3 (student id ,name , sem ,yrs , courses)

I wanted to first check if the student id is in the file and then delete the entire line the id is in if it is

infile = open("students.dat","r")
f = infile.readlines()
id = input('enter your id:')
new_list = []
for line in f:
    for item in line.split(':'):
    new_list.append(item)
    if id in new_list[0]:
        # delete the line its found in
Timus
  • 10,974
  • 5
  • 14
  • 28
  • 1
    Does this answer your question? [How to delete a specific line in a file?](https://stackoverflow.com/questions/4710067/how-to-delete-a-specific-line-in-a-file) – Maurice Meyer Nov 10 '21 at 23:53

1 Answers1

0
with open("students.dat","r") as infile:
f = infile.readlines()
student_id = input('enter your id:')
new_list = []
lines_kept = []
for line in f:
    for item in line.split(':'):
    new_list.append(item)
    if student_id in new_list[0]:
        # delete the line its found in
        print("Found instance")
    else:
        lines_kept.append(line)


# Writing part
with open("students.dat","w") as outfile:
    outfile.write("\n".join(lines_kept))
Larry the Llama
  • 958
  • 3
  • 13