我有以下標題的預訂 CSV 文件:名字、姓氏、預訂日期、主題、課程時間、班級人數(shù)我想閱讀 CSV 文件,只打印預訂日期為“(特定值)”和課程時間為“(特定值”)的行到目前為止,我的代碼是:check_date = "11/01/2019"check_period = "Lesson 3"with open("Bookings.csv") as f: reader = csv.reader(f) header = next(reader) found = False for line in reader: if line[2] == check_date and line[4] == check_period: for line in reader: print(line) found = True break if not found: print("No bookings for", check_date, " ", check_period)但是,不是輸出日期為“11/01/2019”且課程時間為“第 3 課”的行 - 而是使用此標準打印第一行,忽略其余行,并在此之后打印下一行。下面的屏幕截圖:(顯示代碼、輸出和 CSV 示例)
3 回答

Smart貓小萌
TA貢獻1911條經(jīng)驗 獲得超7個贊
您的問題在以下部分:
if line[2] == check_date and line[4] == check_period:
for line in reader:
print(line)
消除 for line in reader:
你試圖在沒有進一步檢查的情況下繼續(xù)循環(huán)你的數(shù)據(jù),這也搞砸了你的外循環(huán)
正如 asmox 所提到的,也刪除了break聲明
添加回答
舉報
0/150
提交
取消