pythonfileinputtruncateseek

How to remove a specific line on a text file base on 2 user inputs with Python?


So far this is what I have. I'm trying to make it so that the program asks for the user to input the author of a book and the ISBN of a book, then if there is a line in the file that contains both of these variables, it will remove that line completely.


print()
            print("Removing a Book")
            print()
            removebookAuthor=(input("Provide the author of the book you would like to remove>"))
            removebookISBN=(input("Provide the ISBN of the book you would like to remove>"))
            with open("books.txt","r+") as f:
                new_f = f.readlines()
                f.seek(2)
                for line in new_f:
                    if "removebookAuthor"+"removebookISBN" in line:
                        f.write(line)
                f.truncate()

For reference, the text document looks something like this:

Python Crash Course - 2nd Edition;Matthes,Eric;978-1593279288;005.133/MAT;12;8;
Python for Dummies;Maruch,Stef;978-0471778646;005.133/MAR;5;0;
Beginning Programming with Python for Dummies;Mueller,John Paul;978-1119457893;005.133/MUE;7;5;
Beginning COBOL for Programmers;Coughlan,Michael;978-1430262534;005.133/COU;1;0;

Example of removebookAuthor would be "Maruch,Stef" Example of removebookISBN would be "978-0471778646"

So far, the program completely clears the entire document. Not too sure how to go about fixing this. Help would be appreciated!


Solution

  • Your if condition is not written correctly. You could use not in for your both conditions:

    removebookAuthor = input("Provide the author of the book you would like to remove>")
    removebookISBN = input("Provide the ISBN of the book you would like to remove>")
    
    with open("books.txt", "r+") as f:
        lines = f.readlines()
        f.seek(2)
        for line in lines:
            if removebookAuthor not in line and removebookISBN not in line:
                f.write(line)
        f.truncate()