用csv文件循环的python

时间:2017-05-01 06:31:10

标签: python csv

此代码打印csv文件的前两行:

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

如何将上面的代码集成到下面的代码中? (我希望sendPackage两行)

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

2 个答案:

答案 0 :(得分:1)

还有其他方法,但这是直截了当的答案正是你所要求的:

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)

答案 1 :(得分:1)

更简洁的方法是使用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

此代码最多从reader获取2个元素。如果少于2个元素,它在迭代后停止。