首页 > 解决方案 > 将标题与数据集的其余部分分开

问题描述

我正在读取一个 csv 文件,然后尝试将标题与文件的其余部分分开。hn 变量是没有第一行的读入文件。hn_header 应该是数据集中的第一行。如果我只定义这两个变量之一,则代码有效。如果我同时定义了它们,那么后面写的那个不包含任何数据。这怎么可能?

from csv import reader

opened_file =  open("hacker_news.csv")
read_file = reader(opened_file)
hn = list(read_file)[1:]     #this should contain all rows except the header
hn_header = list(read_file)[0] # this should be the header



print(hn[:5]) #works 
print(len(hn_header)) #empty list, does not contain the header

标签: python-3.xcsv

解决方案


CSV 阅读器只能遍历文件一次,这是在您第一次将其转换为列表时执行的。为避免需要多次迭代,您可以将列表保存到变量中。

hn_list = list(read_file)
hn = hn_list[1:]
hn_header = hn_list[0]

或者您可以使用扩展的可迭代解包来拆分文件

hn_header, *hn = list(read_file)

推荐阅读