创建任何非空的csv文件并调用此test.csv。考虑一下代码
import csv
with open("test.csv") as read_file:
#this test case also applies to csv.reader()
check_file = csv.DictReader(read_file)
#1) with a nonempty csv file, this will return a nonempty output
for row in check_file:
print(row)
#2) this will not return any output
for row in check_file:
print(row)
换句话说,对check_file
行的迭代删除了check_file
中的所有数据,因此1)返回非空输出,但完全相同的函数2)根本不返回输出。
有一个简单但不优雅的解决方案:
import csv
with open("test.csv") as read_file:
#this test case also applies to csv.reader()
check_file = csv.DictReader(read_file)
#1) with a nonempty csv file, this will return a nonempty output
for row in check_file:
print(row)
with open("test.csv") as read_file:
check_file = csv.DictReader(read_file)
#2) this will return the same output as 1)
for row in check_file:
print(row)
对这种奇怪行为的解释是什么?
发布于 2020-07-22 14:13:47
csv.DictReader
不会将整个数据读入内存,而是充当一个迭代器,它根据需要从read_file
中消耗行,而文件对象read_file
则会根据需要从文件中读取行。当第一个循环完成时,文件指针定位在文件的末尾,第二次迭代将不会得到更多的行。但是,如果您将文件指针倒带到第一行的末尾(与实例化csv.DictReader
后的位置相同,并且它已经读取了标题行),那么您可以使用现有的对象再次迭代,而不必重新打开文件并创建一个新的DictReader
对象。
import csv
with open("my.csv") as read_file:
check_file = csv.DictReader(read_file)
#1) with a nonempty csv file, this will return a nonempty output
for row in check_file:
print(row)
read_file.seek(0) # <==== back to the start
next(read_file) # <==== discard the header row
#2) this will now give you output again...
for row in check_file:
print(row)
类似的考虑也适用于csv.reader()
,尽管在这种情况下,如果您想再次重复相同的输出,您只需返回开始,之后就不会跳过标题行。
https://stackoverflow.com/questions/63043827
复制