hughesdan
hughesdan

Reputation: 2851

Why does the incrementor at the end of this While statement not fire

I would like to nest a for statement inside of a while loop. However, in the following example variable d does not increment by one day after the completion of the for statement. I determined this by printing d out to my screen.

while d <= end:
    for row in reader:
        rowDate = datetime.datetime.strptime(row[0], "%m/%d/%Y")
        if row[1] == offer and rowDate == d:
            rowList.append("1")
    d += datetime.timedelta(days=1)

When I indent the incrementor as follows, it does execute. But this is not the desired result as I do not want it to increment upon each iteration of the for statement.

while d <= end:
    for row in reader:
        rowDate = datetime.datetime.strptime(row[0], "%m/%d/%Y")
        if row[1] == offer and rowDate == d:
            rowList.append("1")
        d += datetime.timedelta(days=1)

There's probably something fundamental to Python that I'm failing to grasp. Can someone please explain why d increments in the second example but not in the first?

Upvotes: 2

Views: 114

Answers (1)

Avaris
Avaris

Reputation: 36715

csv.reader returns a generator. Once you go over it, it is consumed. You can't iterate over it twice without re-instantiating it. That's because generally you don't need to go over it more than once. You can rewrite your code like this:

for row in reader:
    rowDate = datetime.datetime.strptime(row[0], "%m/%d/%Y")
    if row[1] == offer and start_date<=rowDate<=end_date:
        # start_date and end_date are datetime objects
        rowList.append("1")

Upvotes: 2

Related Questions