0

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)

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.