How to delete a line(input) in the list in Python
Question: I have a text file which has multiple lines.

the line string format is [studentnumber, course, specialisation]

studentnumber as ID, course name, specialisation

how can i delete the line containing specific ID with user input

for example:

ID = 12345678

if the ID 12345678 exists, delete the line: "[12345678, ABC, DE]" in the text
and print "The student was deleted from the file"

and if not print "The student does not exist in the file"?

This is what i have so far:

    
    
        studentList = []
        studentFile = open ("students1.txt", "r")
        for line in studentFile:
            smallList = (line.rstrip()).split()
            studentList.append(smallList)
        studentFile.close()
    
        deleteNumber = input("Enter number: ")
        if len(deleteNumber) == 0:
            print("WARNING: Input can not blank -- Please do again!")
            Delete()
        while len(deleteNumber) != 8:
            print("Student number must have 8 digits")
            deleteNumber = input("Please try again: ")
    
        with open("students1.txt") as studentList, \
             open("students1.txt", "w") as studentList:
            for line in studentList:
                if deleteNumber not in line:
                    studentList.write(line)
                    print("The student was deleted from the file…!")          
            else:
                print("The student does not exist in the file…!")
    

It did not work. My lecturer said that i have to delete from the list first.
After that, copy the list to the file. However, i do not know how?

Thank you very much for helping!


Answer: Try something like:

    
    
    import re
    id_to_delete = input('Enter ID u want to delete from file: ')
    filename = 'test.txt'
    get_id = re.compile(r'\d+')
    with open(filename, 'r+') as f:
        for idx, line in enumerate(f, 1):
            line_id = get_id(line)
            if line_id is not None and line_id.group() == id_to_delete:
                print('{data} at line {line_no}'.format(data= line, line_no= idx)
                break
        else:
            print('given {id} can not be find in file'.format(id= id_to_delete)
    

It prints the line number if given id exist (as you said), however it's not
deleting it from file.

