Reading csv file

Peter Otten __peter__ at web.de
Tue Dec 17 03:20:48 EST 2013


Igor Korot wrote:

> Hi, ALL,
> Is there a better way to do that:
> 
> def Read_CSV_File(filename):
>       file = open(filename, "r")
>       reader = csv.DictReader(file)
>       line = 1
>       for row in reader:
>           if line < 6:
>              reader.next()
>              line++
> # process the CSV
> 
> Thank you.

You mean a way that works?

line++

is a syntax error in Python. If you fix that

line = 1
for row in reader:
    if line < 6:
        reader next()
        line += 1

You are still reading the complete csv file. Assuming 

(1) the first row of the csv contains the column names
(2) you want to skip the first five rows of data

you'd have to write

reader = csv.Reader(file)
line = 0
while line < 5:
    next(reader)
    line += 1
for row in reader:
    .... # process csv row

A simpler alternative is to use itertools.islice():

for row in itertools.islice(reader, 5, None):
    ... # process csv row





More information about the Python-list mailing list