在循环中跳过CSV文件的第一行(字段)?

61 投票
3 回答
181232 浏览
提问于 2025-04-17 14:37

可能重复的问题: 在处理CSV数据时,如何忽略第一行数据?

我正在用Python打开一个CSV文件。我在使用循环处理数据,但我需要跳过第一行,因为那一行是表头。

到目前为止,我记得的代码大概是这样的,但好像缺少了什么:我想知道有没有人知道我想做的事情的代码。

for row in kidfile:
    if row.firstline = false:  # <====== Something is missing here.
        continue
    if ......

3 个回答

28

csvreader.next() 是一个方法,它会从读取器的可迭代对象中返回下一行数据,并把这一行的数据按照当前的格式解析成一个列表。

140

有很多方法可以跳过第一行。除了Bakuriu提到的那些,我还想补充一些:

with open(filename, 'r') as f:
    next(f)
    for line in f:

还有:

with open(filename,'r') as f:
    lines = f.readlines()[1:]
80

最好的做法是在把文件对象传给csv模块后,跳过表头部分:

with open('myfile.csv', 'r', newline='') as in_file:
    reader = csv.reader(in_file)
    # skip header
    next(reader)
    for row in reader:
        # handle parsed row

这样可以正确处理多行的CSV表头。


旧的回答:

你可能想要的是这样的:

firstline = True
for row in kidfile:
    if firstline:    #skip first line
        firstline = False
        continue
    # parse the line

还有一种方法可以达到相同的效果,就是在循环之前调用readline

kidfile.readline()   # skip the first line
for row in kidfile:
    #parse the line

撰写回答