![](/img/trans.png)
[英]How can we skip lines automatically in excel and csv file until header row is found in python (pyspark)
[英]Can't skip header row in csv file with python
我在 python 中使用 CSV 模块将 CSV 读入内存,我需要跳过标题行。
我正在使用下一个命令跳过标题,但它不起作用。
import csv
with open(aws_env_list) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
标题仍在生成中,使我的脚本崩溃。 我的脚本生成以下行:
Working in AWS Account: companyAccountName,AWSAccountName,Description,LOB,AWSAccountNumber,CIDRBlock,ConnectedtoMontvale,PeninsulaorIsland,URL,Owner,EngagementCode,CloudOpsAccessType
在原始 CSV 中,标题仅在第一行。
上面有什么问题,为什么不跳过标题? 有没有更好的办法?
我认为您没有正确使用 next() 函数。
这是文档中的示例:
import csv
with open('eggs.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print(', '.join(row))
当您使用 csv.reader 时,它会获取 csv 文件并为每一行创建一个可迭代对象。 因此,如果您想跳过第一行(标题行),只需进行此更改。
with open(aws_env_list) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in list(csv_reader)[1:]:
""" do whatever action """
当您将 [1:] 添加到 csv_reader 的末尾时,它会告诉它只选择第二个对象(因为 0 是第一个)。 您实质上创建了不包含第一个元素的对象子集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.