58

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

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 ......
martineau
  • 119,623
  • 25
  • 170
  • 301
Raitis Kupce
  • 760
  • 2
  • 7
  • 16
  • Why would someone show you but not let you take notes, and why is that relevant to your question? – danodonovan Feb 03 '13 at 16:12
  • Use `csv_data.__next__()` for 3.x and `csv_data.next()` for 2.x. More details are https://stackoverflow.com/a/63096202/10961238 – Romil Patel Jul 26 '20 at 04:52

3 Answers3

136

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

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

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]
Andrea
  • 3,627
  • 4
  • 24
  • 36
78

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

This handles multiline CSV headers correctly.


Older answer:

Probably you want something like:

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

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
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
28

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

user2037553
  • 281
  • 1
  • 3
  • 2
  • 14
    In python3, the method is `reader.__next__()`, which should be called by using `next(reader)` – travc May 07 '15 at 20:11