如何通过用户输入从CSV文件筛选并打印指定作者的书籍
Hey there! I see you've got a solid start with storing book records in a CSV file—great work! Let's build on that to add the author lookup feature you want. First, let's tweak your existing code for efficiency, then add the lookup functionality.
First: Optimize Your Data Entry Code
Right now, you're opening the CSV file every time you add a new book, which isn't the most efficient. Let's move the while loop inside the initial with block so we only open the file once for writing:
import csv amount = int(input("How many records would you like to store: ")) # Open the file once for writing (creates it if it doesn't exist) with open("Books.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["", "Book", "Author", "Year released"]) # Header row count = 0 while count < amount: count += 1 book = input("Enter a book: ") author = input("Enter its Author: ") # Fixed the typo "it's" to "its" year = input("Enter the year it released: ") writer.writerow([count, book, author, year])
Now: Add the Author Lookup Feature
Next, we'll add a section where the user can enter an author's name, and the program will pull up all books by that author. We'll read the CSV file, loop through each row, and match the author name:
# After data entry, let's add the lookup feature print("\n--- Look Up Books by Author ---") target_author = input("Enter the author's name to find their books: ").strip() # Open the CSV file for reading with open("Books.csv", "r") as file: reader = csv.DictReader(file) # Using DictReader makes it easier to access columns by name found_books = [] for row in reader: # Compare the author name (case-insensitive so "J.K. Rowling" and "j.k. rowling" both work) if row["Author"].strip().lower() == target_author.lower(): found_books.append(f"{row['Book']} (Released in {row['Year released']})") if found_books: print(f"\nBooks by {target_author}:") for book in found_books: print(f"- {book}") else: print(f"\nSorry, no books found for author '{target_author}'.")
Putting It All Together
Here's the full combined code that lets users add books AND look them up by author:
import csv # Step 1: Collect and store book records amount = int(input("How many records would you like to store: ")) with open("Books.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["", "Book", "Author", "Year released"]) count = 0 while count < amount: count += 1 book = input("Enter a book: ") author = input("Enter its Author: ") year = input("Enter the year it released: ") writer.writerow([count, book, author, year]) # Step 2: Author lookup feature print("\n--- Look Up Books by Author ---") target_author = input("Enter the author's name to find their books: ").strip() with open("Books.csv", "r") as file: reader = csv.DictReader(file) found_books = [] for row in reader: if row["Author"].strip().lower() == target_author.lower(): found_books.append(f"{row['Book']} ({row['Year released']})") if found_books: print(f"\n📚 Books by {target_author}:") for idx, book in enumerate(found_books, 1): print(f"{idx}. {book}") else: print(f"\nNo books found for '{target_author}'. Try checking the spelling!")
Key Notes:
- Used
csv.DictReaderto access columns by their header names (likerow["Author"]) instead of index numbers—this makes the code easier to read and maintain. - Added case-insensitive matching so users don't have to worry about exact capitalization.
- Fixed a small typo in your original code ("it's" → "its" since we're talking about possession, not a contraction).
内容的提问来源于stack exchange,提问作者sdrr453e

