如何在Python命令行中使用TinyDB删除指定数据?
Fixing the Delete Functionality for Your TinyDB Setup
Hey there! Let's get that delete feature working properly. Right now your code is successfully finding entries that match your criteria, but it's not actually removing them from the database. Here's how to tweak your code to make it delete targeted entries:
Updated Code Snippet
elif command == 'del' or command == 'delete': Cat_Del = input('Which Category do you wanna delete: ') Name_Del = input('Whats the name ') from tinydb import Query Item = Query() # Use TinyDB's remove() method with combined search criteria deleted_entries = db.remove((Item['Category'] == Cat_Del) & (Item['Naam'] == Name_Del)) # Give clear feedback to the user if deleted_entries: print(f"Successfully deleted {len(deleted_entries)} entry(ies)!") else: print("Oops, no entries matched your category and name.") # Optional: Show updated database to confirm changes print("\nCurrent database content:") print(db.all())
Key Changes Explained
- Replace
search()withremove(): Thesearch()method only returns matching entries, butremove()does the actual deletion and gives you back the list of entries it deleted—perfect for confirming what was removed! - Fix the logical operator: TinyDB uses
&(ampersand) for "AND" in queries instead of Python's regularand. Usingandwould break the query logic because it evaluates to a boolean, whereas&keeps the query conditions intact for TinyDB to parse correctly. - Add user feedback: Now you'll know right away if the deletion worked or if there were no matching entries—no more guessing!
Test It Out
With your sample database:
{"_default": {"1": {"Category": "Fruit", "SubCategory": "zoet", "Naam": "appel", "Cost": "$5"}, "2": {"Category": "Fruit", "SubCategory": "zoet", "Naam": "banaantje", "Cost": "$10"}}}
If you input Fruit as the category and appel as the name, the code will delete the first entry. Your database will then look like this:
{"_default": {"2": {"Category": "Fruit", "SubCategory": "zoet", "Naam": "banaantje", "Cost": "$10"}}}
内容的提问来源于stack exchange,提问作者HighTechGamingNL
相关产品推荐
相关产品推荐

