[英]How do print the data between two dates set by user in my CSV file?
I have made a CSV file where it stores a book, its author and the year it was published (this file is made from user input).我制作了一个 CSV 文件,其中存储了一本书、其作者和出版年份(此文件由用户输入制作)。 Now I want to ask the user for a starting year and an ending year, and the program should display all the books from the data set published during that time frame.
现在我想询问用户的开始年份和结束年份,程序应该显示在该时间范围内发布的数据集中的所有书籍。 I'm just not sure how to do this
我只是不知道该怎么做
Here is my code so far:到目前为止,这是我的代码:
import csv
amount = int(input("How many records would you like to add: "))
count = 0
with open("Books.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["", "Book", "Author", "Year released"])
while count < amount:
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", newline="") as f:
writer = csv.writer(f)
writer.writerow(headers)
count += 1
you can read a csv using pandas.read_csv .您可以使用pandas.read_csv 读取 csv 。
import pandas as pd
df = pd.read_csv("Books.csv")
Now you can filter records from based on year column现在您可以根据年份列过滤记录
filter = (df['Year released'] > start_date) & (df['Year released'] <= end_date)
filter_df = df.loc[filter]
To select the books:至 select 书籍:
books = filter_df['Book'].tolist()
Pandas is a very good option as Rajat Mishra said - you could also do it with the built-in CSV module:正如 Rajat Mishra 所说,Pandas 是一个非常好的选择 - 你也可以使用内置的 CSV 模块来做到这一点:
books = []
with open("books.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
count, book, author, release_year = row
print(row)
if release_year is int:
if int(release_year) > start_year and int(release_year) < end_year:
books.append(book)
print(books)
I believe that you are able to sort the column by using the built-in sorted function.我相信您可以使用内置的 sorted function 对列进行排序。
import operator
with open("Books.csv", "r") as f:
reader = csv.reader(f)
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=False)
We send 3 parameters to the sorted function:我们向排序后的 function 发送 3 个参数:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.