简体   繁体   中英

Python CSV Reader Control Flow

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM