user2475523
user2475523

Reputation: 53

For Loop for n iterations-Python

I have a simple for loop in a Python script:

for filename in filenames:
    outline = getinfo(filename)
    outfile.write(outline)

This for loop is part of a larger script that extracts data from HTML pages. I have nearly 6GB of HTML pages and want to do some test runs before I try it on all of them.

How can I make the loop break after a set number of iterations (lets say 100)?

Upvotes: 3

Views: 11635

Answers (4)

Orkun Berk Yuzbasioglu
Orkun Berk Yuzbasioglu

Reputation: 165

Use the built-in function enumerate(), available in both Python 2 and 3.

for idx,filename in enumerate(filenames):
    if idx == 100:
        break
    outline= getinfo(filename)
    outfile.write(outline)

Also look at this.

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142126

I like @kqr's answer, but just another approach to consider, instead of taking the first 100, you could take a random n many instead:

from random import sample
for filename in sample(filenames, 10):
    # pass

Upvotes: 2

kqr
kqr

Reputation: 15028

for filename in filenames[:100]:
    outline= getinfo(filename)
    outfile.write(outline)

The list slice filenames[:100] will truncate the list of file names to just the first 100 elements.

Upvotes: 13

waldol1
waldol1

Reputation: 1881

Keep a counter for your for loop. When your counter reaches, 100, break

counter = 0
for filename in filenames:
    if counter == 100:
        break
    outline= getinfo(filename)
    outfile.write(outline)
    counter += 1

Upvotes: 9

Related Questions