Search code examples
pythontext-filesdelete-row

how to delete a line from a txt file using python?


I have a file with data about students such as their name, address, grades, etc. I created a function that would delete a whole line from a text file based on a student's First Name and Last Name. This function worked correctly. However, afterward, I decided to update it so that if the user entered a name that was not in the file it would print: Student not found. However, now even, if the user types in a name that is in the file it still prints: student not found...

Here is my code:

def delete_a_record(filename):

    x=input("Remove First Name:")
    y=input("Remove Last Name:")

    with open(filename, "r") as f:
        lines = f.readlines()
    with open(filename, "w") as f:
        for i in lines:
            t=i.split()
            if t[0]!=x and t[1]!=y:
                f.write(i)
            elif x or y not in t:
                print("Student Not Found")




    f.close()
delete_a_record("mytextfile.txt")

Could someone explain to me why?


Solution

  • For what I undestood(correct me if I'm wrong), I guess there is two issues in your logic.

    1. If you mean to test if both x and y are not in t you should test it separatelly, like:
    if t[0]!=x and t[1]!=y:
        f.write(i)
    elif x not in t and y not in t:
        print("Student Not Found")
    

    The way it is now, if x is not None, the condition elif x or ... will always return true because x evaluates to True.

    1. If you want to check if the student is not in the entire file, I think you should not be testing this for each line you read. Since you don't know in which line the student might be, maybe you could reorganize your code to process the whole file first before testing if the student was not found.