Python新手求助:商品删除功能的文件操作代码异常问题
Fixing Your Python Product Deletion Code
Hey there! Let's break down the issues in your code and get that product deletion feature working properly. Here's what's going wrong, plus a corrected version of your code with explanations:
Key Issues in Your Original Code
- You can't directly delete lines from an open file: Using
r+mode anddel linedoesn't modify the actual file—lineis just a temporary variable in your loop, so deleting it does nothing to the stored data. - No logic to write changes back to the file: Even if you correctly adjusted the product quantity, you didn't save those changes to the file.
- Minor spelling error:
delate_productshould bedelete_product(not a breaking issue, but better for readability). - No error handling: If the daily archive file doesn't exist yet, your code will crash immediately.
- Unclosed file resource: You don't explicitly close
f1, which can lead to resource leaks.
Corrected Code
import datetime # Get current date for archive filename date_now1 = datetime.datetime.now() archive_date1 = date_now1.strftime("%d.%m.%Y") # Get user input (clean up whitespace to avoid matching issues) print("What product do you wish to delete?") delete_product = input().strip() try: # Read all lines from the archive file first with open(archive_date1, "r") as f: lines = f.readlines() updated_lines = [] product_found = False # Process each line to update or remove the product for line in lines: cleaned_line = line.strip() if not cleaned_line: # Skip empty lines to avoid errors continue if delete_product in cleaned_line: product_found = True # Split line into product name and quantity product_parts = cleaned_line.split() # Make sure the line has a valid format if len(product_parts) >= 2: try: quantity = int(product_parts[1]) if quantity == 1: # Don't add this line back to remove the product print("Product deleted successfully!") else: # Reduce quantity by 1 and keep the line new_quantity = quantity - 1 updated_line = f"{product_parts[0]} {new_quantity}" updated_lines.append(updated_line) print(f"Product quantity reduced to {new_quantity}") except ValueError: print(f"Warning: Invalid quantity format in line: {cleaned_line}") updated_lines.append(cleaned_line) # Keep invalid line as-is else: print(f"Warning: Malformed line for product: {cleaned_line}") updated_lines.append(cleaned_line) else: # Keep lines that don't match the product updated_lines.append(cleaned_line) # Write the updated content back to the file with open(archive_date1, "w") as f: f.write("\n".join(updated_lines)) if not product_found: print("Error: That product wasn't found in the archive.") except FileNotFoundError: print(f"Error: The archive file {archive_date1} doesn't exist yet.")
What's Improved?
- Safe file handling: Uses
withstatements to automatically close files, preventing resource leaks. - Proper file modification: Reads all content into memory, processes it, then rewrites the entire file—this is the standard way to modify file contents in Python.
- Error resilience: Catches missing files and invalid quantity values, so your program won't crash unexpectedly.
- Better user feedback: Tells you if the product wasn't found, if there's a formatting error, or if the quantity was successfully reduced.
- Cleaner input handling: Uses
strip()to remove extra spaces from user input, so accidental spaces won't break product matching.
内容的提问来源于stack exchange,提问作者Krystian Dorsz
相关产品推荐
相关产品推荐

