python-3.x - 将标题与数据集的其余部分分开
问题描述
我正在读取一个 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
解决方案
CSV 阅读器只能遍历文件一次,这是在您第一次将其转换为列表时执行的。为避免需要多次迭代,您可以将列表保存到变量中。
hn_list = list(read_file)
hn = hn_list[1:]
hn_header = hn_list[0]
或者您可以使用扩展的可迭代解包来拆分文件
hn_header, *hn = list(read_file)
推荐阅读
- ansible - 从 csv 注册条件时的 Ansible
- sql - 使用映射数据流连接多个源
- node.js - 使用 NodeJS 写入 JSON 时如何忽略空值或空白值
- python - 如何使用 Python 和 Panda 将此嵌套的 json 转换为 CSV?
- python - 如何摆脱弃用警告:'np.float' 是内置'float' 的弃用别名
- java - 如何在spring框架中使用.properties/.xml/.yml等配置文件配置注解值?
- sql - 使用关联表的新外键更新表的列
- mysql - 如何在空间 JOIN 上使用组函数来更新 MySQL 中的表?
- python - 如何使用 python 从 firebase 存储文件夹下载图像?
- javascript - 为什么带有 `T17:00:00.000Z` 的 new Date() 返回下一个日期?