I created a CSV file that stores a book, its author and the year the book released, through user input. I want to now ask the user to choose an author and the program should display all the books by that author, but I'm not sure how to do this
Here is my code so far:
import csv
amount = int(input("How many records would you like to store: "))
count = 0
with open("Books.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["", "Book", "Author", "Year released"])
while count < amount:
count += 1
book = input("Enter a book: ")
author = input("Enter it's Author: ")
year = input("Enter the year it released: ")
headers = [count, book, author, year]
with open("Books.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(headers)
This should do.
Example contents of Books.csv
,Book,Author,Year released
0,1984,G. Orwell,1949
1,Brave New World,A. Huxley,1932
2,Johnny Got His Gun,D. Trumbo,1939
The code
import csv
# getting author and book column indexes in the csv
COLUMNS = ["", "Book", "Author", "Year released"] # first column is the book no.
AUTHOR_COLUMN_INDEX = COLUMNS.index("Author")
BOOK_COLUMN_INDEX = COLUMNS.index("Book")
author = input("Enter the name of an author: ")
with open('Books.csv', 'r', newline='') as f:
for line in csv.reader(f):
if len(line) == len(COLUMNS): # if empty line or invalid line
if line[AUTHOR_COLUMN_INDEX] == author:
print(line[BOOK_COLUMN_INDEX])
When the code is run:
Enter the name of an author: A. Huxley
Brave New World
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.