我有一个我正在阅读的csv,大约10-15行包含搜索参数,但我只想写一个新文件,只显示其中的3个,并且无法弄清楚如何做到这一点。
with open('events.csv', 'r', encoding = 'latin-1') as read_file, open('today.txt', 'w', encoding='latin-1') as write_file:
reader = csv.reader(read_file, delimiter=',')
writer = csv.writer(write_file)
for row in reader:
if day in row[0]:
writer.writerow(row)
答案 0 :(得分:0)
只需添加计数器:
n = 0
with open('events.csv', 'r', encoding = 'latin-1') as read_file, open('today.txt', 'w', encoding='latin-1') as write_file:
reader = csv.reader(read_file, delimiter=',')
writer = csv.writer(write_file)
for row in reader:
if day in row[0] and n < 3:
writer.writerow(row)
n += 1
elif n >= 3:
break