使用 CSV 文件跳过循环中的第一行(字段)? [英] Skip first line(field) in loop using CSV file?

查看:35
本文介绍了使用 CSV 文件跳过循环中的第一行(字段)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I am using python to open CSV file. I am using formula loop but I need to skip the first row because it has header.

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

So far I remember was something like this but it is missing something: I wonder if someone knows the code for what I am trying to do.

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

推荐答案

执行此操作的最佳方法是在将文件对象传递给 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

这篇关于使用 CSV 文件跳过循环中的第一行(字段)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆