digi_life
digi_life

Reputation: 109

python for loop with csv file

This code prints the first two rows of a csv file:

with open('myfile.csv', 'r') as f:
    for n, l in enumerate(f):
        if n > 1:
            break
        print l

How do I integrate the code above to the code below? (I am looking to sendPackage for two rows)

with open(sys.argv[1]) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        sendPackage(row, job_id)

Upvotes: 0

Views: 377

Answers (2)

Paul Rooney
Paul Rooney

Reputation: 21619

A neater way is to use itertools.islice.

import csv
import sys
from itertools import islice

def sendPackage(row, job_id):
    print('row {}: job {}'.format(row, job_id))

with open(sys.argv[1]) as csvfile:

    reader = csv.DictReader(csvfile)
    for row in islice(reader, 2):
        sendPackage(row, 1) # dummy value for job_id

This code takes a maximum of 2 elements from reader. If there are less than 2 elements it stops after it has iterated over them.

Upvotes: 1

JohanL
JohanL

Reputation: 6891

There are other ways, but this is the straight forward answer doing exactly what you ask for:

with open(sys.argv[1]) as csvfile:
    reader = csv.DictReader(csvfile)
    for row_num, row in enumerate(reader):
        if row_num > 1:
            break
        sendPackage(row, job_id)

Upvotes: 1

Related Questions