• Post author:
  • Post category:Python
  • Reading time:2 mins read

In Python, while reading a CSV using the CSV module you can skip the first line using next() method. We usually want to skip the first line when the file is containing a header row, and we don't want to print or import that row. The following is an example.

Advertisement

Suppose you have a CSV file containing the following data with a header line. You want to read and print the lines on screen without the first header line.

DEPTNO,DNAME,LOC
10,ACCOUNTING,NEW YORK
20,RESEARCH,DALLAS
30,SALES,CHICAGO
40,OPERATIONS,BOSTON

Example to Skip First Line While Reading a CSV File in Python

Use next() method of CSV module before FOR LOOP to skip the first line, as shown in below example.

Advertisement
import csv

with open("product_record.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    # the below statement will skip the first row
    next(csv_reader)
    for lines in csv_reader:
      print(lines)

Output

['10', 'ACCOUNTING', 'NEW YORK']
['20', 'RESEARCH', 'DALLAS']
['30', 'SALES', 'CHICAGO']
['40', 'OPERATIONS', 'BOSTON']

See also:

Related:  Get Dates of Working Days Between Two Dates in Python (Exclude Weekends)

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.