python - 如何通过用户输入打印 CSV 文件中的某些数据
问题描述
我通过用户输入创建了一个 CSV 文件,用于存储一本书、其作者和该书的发行年份。我现在想要求用户选择一个作者,程序应该显示该作者的所有书籍,但我不知道该怎么做
到目前为止,这是我的代码:
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)
解决方案
这应该做。
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
编码
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])
代码运行时:
Enter the name of an author: A. Huxley
Brave New World
推荐阅读
- python - 地理数据框地图图似乎忽略了 legend_kwds
- json - wso2 使用数组将 xml 转换为 json
- excel - 尝试在 VBA 中创建一个用户表单,该用户表单返回一组基于现有电子表格中数据的标准指定的值
- swift - 使用 PDFKit 删除高亮注释
- selenium - selenium & chrome 78 未能通过基本身份验证
- c# - 使用默认值更改 SQL Server 用户定义类型仍然强制我传递新列
- mobile - Ubuntu 移动宽带
- python - python find index of elements functionally depending on a condition
- swift - 禁用特定表格视图单元格的按钮功能
- excel - 如何将别名设置为发件人帐户?