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

Rai*_*pce 33 python csv for-loop

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

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

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

for row in kidfile:
    if row.firstline = false:  # <====== Something is missing here.
        continue
    if ......
Run Code Online (Sandbox Code Playgroud)

And*_*rea 96

有很多方法可以跳过第一行.除了Bakuriu所说的那些,我还会补充:

with open(filename, 'r') as f:
    next(f)
    for line in f:
Run Code Online (Sandbox Code Playgroud)

和:

with open(filename,'r') as f:
    lines = f.readlines()[1:]
Run Code Online (Sandbox Code Playgroud)


Bak*_*riu 47

可能你想要的东西:

firstline = True
for row in kidfile:
    if firstline:    #skip first line
        firstline = False
        continue
    # parse the line
Run Code Online (Sandbox Code Playgroud)

获得相同结果的另一种方法是readline在循环之前调用:

kidfile.readline()   # skip the first line
for row in kidfile:
    #parse the line
Run Code Online (Sandbox Code Playgroud)

  • `next`函数是一种更简洁的方法. (10认同)

小智 23

csvreader.next()将读者的可迭代对象的下一行作为列表返回,根据当前方言进行解析.

  • 在python3中,方法是`reader .__ next __()`,应该使用`next(reader)` (10认同)