且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-04 12:41:34

执行此操作的***方法是在将文件对象传递给 csv 模块之后 跳过标题:

The best way of doing this is skipping the header after passing the file object to the csv module:

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 标头.

This handles multiline CSV headers correctly.

旧答案:

可能你想要这样的东西:

Probably you want something like:

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

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

An other way to achive the same result is calling readline before the loop:

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