55

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

我正在使用 python 打开 CSV 文件。我正在使用公式循环,但我需要跳过第一行,因为它有标题。

到目前为止,我记得是这样的,但它缺少一些东西:我想知道是否有人知道我正在尝试做的事情的代码。

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

3 回答 3

130

有很多方法可以跳过第一行。除了Bakuriu所说的之外,我还要补充:

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

和:

with open(filename,'r') as f:
    lines = f.readlines()[1:]
于 2013-02-03T16:06:40.857 回答
72

最好的方法是在将文件对象传递给模块跳过标头: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
于 2013-02-03T16:03:04.717 回答
28

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

于 2013-02-03T17:04:29.273 回答