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

2024-05-09 23:09:11 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:When processing CSV data, how do I ignore the first line of data?

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

到目前为止,我记得是这样的,但它缺少了一些东西:我不知道是否有人知道我要做什么的代码。

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

Tags: ofcsvthedataiflinedohow
3条回答

csvreader.next() 将读取器的iterable对象的下一行作为列表返回,并根据当前方言进行解析。

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

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

以及:

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

可能你想要这样的东西:

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

相关问题 更多 >