Delete a row from a text file with Python

前端 未结 5 1933
说谎
说谎 2020-12-19 15:43

I have a file where each line starts with a number. The user can delete a row by typing in the number of the row the user would like to delete.

The issue I\'m having

5条回答
  •  不思量自难忘°
    2020-12-19 16:29

    You don't need to check for the lines numbers in your file, you can do something like this:

    def DeleteToDo(self):
        print "Which Item Do You Want To Delete?"
        DeleteItem = int(raw_input(">")) - 1
        print "Are You Sure You Want To Delete Number" + str(DeleteItem) + "(y/n)"
        VerifyDelete = str.lower(raw_input(">"))
        if VerifyDelete == "y":
            with open(ToDo.filename,"r") as f:
                lines = ''.join([a for i,a in enumerate(f) if i != DeleteItem])
    
            with open(ToDo.filename, "w") as f:
                f.write(lines)
        else:
            print "Nothing Deleted"
    

提交回复
热议问题