对于读限制python中的行

时间:2014-11-13 20:24:37

标签: python python-2.7 loops

我只想执行此循环rownum次:

rownum = 1000
with open('outputfile.csv', 'wb') as out:
    with open('inputfile.csv', 'rbU') as ifile:
        out_writer = csv.writer(out)
        for row in read:
            out_writer.writerow(row)

插入像for i in range(0, rownum):这样的东西不起作用,但我也无法理解它放在哪里。我怎么说for y in x N times

2 个答案:

答案 0 :(得分:4)

使用itertools.islice

for row in itertools.islice(read, stop = rownum):
    out_writer.writerow(row)

答案 1 :(得分:0)

如果您不想导入itertools,还可以使用enumeratebreak

    for rowidx, row in enumerate(read):
        if rowidx == MAX_ROWS: break
        out_writer.writerow(row)

itertools更像是pythonic。