首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >为什么行上的迭代要删除csv.reader和csv.DictReader中的数据?

为什么行上的迭代要删除csv.reader和csv.DictReader中的数据?
EN

Stack Overflow用户
提问于 2020-07-22 22:01:25
回答 1查看 223关注 0票数 0

创建任何非空的csv文件并调用此test.csv。考虑一下代码

代码语言:javascript
代码运行次数:0
运行
复制
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)根本不返回输出。

有一个简单但不优雅的解决方案:

代码语言:javascript
代码运行次数:0
运行
复制
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)

对这种奇怪行为的解释是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-22 22:13:47

csv.DictReader不会将整个数据读入内存,而是充当一个迭代器,它根据需要从read_file中消耗行,而文件对象read_file则会根据需要从文件中读取行。当第一个循环完成时,文件指针定位在文件的末尾,第二次迭代将不会得到更多的行。但是,如果您将文件指针倒带到第一行的末尾(与实例化csv.DictReader后的位置相同,并且它已经读取了标题行),那么您可以使用现有的对象再次迭代,而不必重新打开文件并创建一个新的DictReader对象。

代码语言:javascript
代码运行次数:0
运行
复制
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(),尽管在这种情况下,如果您想再次重复相同的输出,您只需返回开始,之后就不会跳过标题行。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63043827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档