0

I was fairly surprised to see this functionality in Python's CSV reader.

with open(sys.argv[1]) as csvfile:
    reader = csv.DictReader(csvfile)
    for i in range(3):
        sys.stdout.write('A ')
        for row in reader:
            sys.stdout.write('B ')

#sys.argv[1] is a 3 row csv file

I would normally expect code like this to print out something like:

A B B B A B B B A B B

But instead I get:

A B B A A

This seems to violate the basic flow control properties of for loops as I understand them. I mainly suspect that there is an unusual property of this iterator that results in this behavior. Any explanation would helpful and very much appreciated. Thank you.

1 Answer 1

2

Your reader object from csv.DictReader is a generator. It got exhausted in the first iteration of the outer for. So in the following iterations, the inner for loop has no items to execute the loop.

Sign up to request clarification or add additional context in comments.

5 Comments

Okay. I think I can fix that by switching the places of the two for loops. Thank you.
@LucaDelSignore Yes, you can. But you can also store the items from the reader in a list, if the csv file isn't too large
Actually, the real CSV file is very large.
Oh, then might be better to switch the loops
Thanks man. I appreciate the help and not getting down voted into oblivion for being inexperienced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.