当前位置: 动力学知识库 > 问答 > 编程问答 >

python loop through number of rows at a time

问题描述:

Im trying to loop through a number of N rows at a time in a text file . How do I loop through the whole file for instance say it has 100 rows and print 10 at a time.

This is how far I got.

 N=10

f=open("data.txt")

for i in range(N):

line=f.next().strip()

print line

f.close()

网友答案:

You could treat the file as an iterator and just take extra items from it on each iteration:

with open('data.txt') as f:
    for line in f:
        lines = [line] + [next(f) for _ in xrange(9)]  # have 1 already, so need 9
        # process lines

If your file length is not divisible by your chunk size, you can use next(f, None) instead, and filter out the Nones before processing lines.

分享给朋友:
您可能感兴趣的文章:
随机阅读: