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

时间:2020-04-14 17:00:42

标签: python python-3.x

所以我有这两个for循环,第一个循环通过csv阅读器,第二个循环通过csv DictReader。当打印结果时,我看到第一行是从第一行开始,第二行是从第二行开始,我不知道为什么,因为这是一个新循环。当我注释掉第一行时,第二行通常从第一行开始。这是代码:

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

1 个答案:

答案 0 :(得分:1)

您正在读取同一个打开的文件对象,因此您的第一个Appcelerator Command-Line Interface, version 8.0.0 Copyright (c) 2014-2020, Appcelerator, Inc. All Rights Reserved. Operating System Name = Mac OS X Version = 10.13.6 Architecture = 64bit # CPUs = 4 Memory = 4.0GB Node.js Node.js Version = 12.16.2 npm Version = 6.14.4 Appcelerator CLI Installer = 5.0.0 Core Package = 8.0.0 Titanium CLI CLI Version = 5.2.2 node-appc Version = 0.2.49 Titanium SDKs 9.0.0.GA Version = 9.0.0 Install Location = /Users/posuna/Library/Application Support/Titanium/mobilesdk/osx/9.0.0.GA Platforms = iphone, android git Hash = ff53751424 git Timestamp = 3/4/2020 14:47 node-appc Version = 0.3.4 Mac OS X Command Line Tools = installed Intel® Hardware Accelerated Execution Manager (HAXM) Not installed Java Development Kit Version = 1.8.0_241 Java Home = /Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home Genymotion Path = not found Genymotion Executable = not found Genymotion Player = not found Home = not found VirtualBox Executable = not found Version = unknown Android SDK Android Executable = not found ADB Executable = not found SDK Path = not found Android NDK NDK Path = not found NDK Version = not found Android Platforms None Android Add-Ons None Android Emulators None Genymotion Emulators None Connected Android Devices None Xcode 10.1 (build 10B61) - Xcode default Install Location = /Applications/Xcode.app/Contents/Developer iOS SDKs = 12.1 iOS Simulators = none Watch SDKs = 5.1 Watch Simulators = none Supported by TiSDK 9.0.0.GA = yes EULA Accepted = yes Teams = none 从第一行未读开始,headerReaderReader = csv.reader(csvFile)从下一个未读行开始。如果您将它们重新排序为

headerReaderDict = csv.DictReader(csvFile)

然后headerReaderDict = csv.DictReader(csvFile) headerReaderReader = csv.reader(csvFile) for row in headerReaderReader: print(row) break for row in headerReaderDict: print(row) break 从第二行开始,headerReaderReader从第一行开始。

如果确实需要打开同一文件的2个副本,则需要维护2个不同的对象以避免共享相同的指针:

headerReaderDict