[英]How do I go to the first record of a CSV file within the same “for” loop?
我在這里問了一個類似的問題,我得到的答案是使用seek()
方法。 現在我正在做以下事情:
with open("total.csv", 'rb') as input1:
time.sleep(3)
input1.seek(0)
reader = csv.reader(input1, delimiter="\t")
for row in reader:
#Read the CSV row by row.
但是,我想在同一個for循環中導航到CSV的第一條記錄。 我知道我的循環不會以這種方式終止,但這正是我想要的。 我不希望for
循環結束,如果它到達最后一條記錄,我想導航回第一條記錄並重新讀取整個文件(並繼續閱讀)。 我怎么做?
謝謝!
它必須在for
-loop中嗎? 您可以像這樣(未經測試)實現此行為:
with open("total.csv", 'rb') as input1:
time.sleep(3)
reader = csv.reader(input1, delimiter="\t")
while True:
input1.seek(0)
for row in reader:
#Read the CSV row by row.
為簡單起見,創建一個生成器:
def repeated_reader(input, reader):
while True:
input.seek(0)
for row in reader:
yield row
with open("total.csv", 'rb') as input1:
reader = csv.reader(input1, delimiter="\t")
for row in repeated_reader(input1, reader):
#Read the CSV row by row.
我實際上計算了CSV中的總行數,當我在最后一行時,我做了input1.seek(0)
row_count = sum(1 for row in csv.reader(open('total.csv')))
print row_count
row_count2 = 0
with open("total.csv", 'rb') as input1:
time.sleep(3)
input1.seek(0)
reader = csv.reader(input1, delimiter="\t")
for row in reader:
count += 1
#Read the CSV row by row.
if row_count2 == row_count:
row_count2 = 0
time.sleep(3)
input1.seek(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.