简体   繁体   English

Python - 为什么第二个 for 循环从第二行开始

[英]Python - Why does the second for loop start from the second row

So I have these two for loops, the first one loops through a csv reader and the second loops through a csv DictReader.所以我有这两个 for 循环,第一个循环通过 csv 阅读器,第二个循环通过 csv DictReader。 When results are printed I see that the first one is starting from the first row and the second is starting from the second row which I don't know why as it's a new loop.打印结果时,我看到第一个从第一行开始,第二个从第二行开始,我不知道为什么,因为它是一个新循环。 When I comment out the first one, the second one starts normally from the first row.当我注释掉第一个时,第二个通常从第一行开始。 Here is the code:这是代码:

csvFile = open('contactscsv.csv', 'r')
headerReaderReader = csv.reader(csvFile)
headerReaderDict = csv.DictReader(csvFile)

for row in headerReaderReader:
    print(row)
    break

for row in headerReaderDict:
    print(row)
    break

You are reading from the same open file object, so your first headerReaderReader = csv.reader(csvFile) is starting from the first unread row and headerReaderDict = csv.DictReader(csvFile) is starting from the next unread row.您正在从同一个打开的文件 object 中读取,因此您的第一个headerReaderReader = csv.reader(csvFile)从第一个未读行开始,而headerReaderDict = csv.DictReader(csvFile)从下一个未读行开始。 If you reordered them to be如果您将它们重新排序为

headerReaderDict = csv.DictReader(csvFile)
headerReaderReader = csv.reader(csvFile)

for row in headerReaderReader:
    print(row)
    break

for row in headerReaderDict:
    print(row)
    break

then headerReaderReader will start from the second row and headerReaderDict will start from the first.然后headerReaderReader将从第二行开始, headerReaderDict将从第一行开始。

If you really need to open 2 copies of the same file, you will need to maintain 2 different objects to avoid sharing the same pointer:如果你真的需要打开同一个文件的 2 个副本,你将需要维护 2 个不同的对象以避免共享相同的指针:

with open('contactscsv.csv', 'r') as csv1, open('contactscsv.csv', 'r') as csv2:
    headerReaderReader = csv.reader(csv1)
    headerReaderDict = csv.DictReader(csv2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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