4

For example, I need to read a file by calling readline for 10 times.

with open("input") as input_file:
    for i in range(10):
        line = input_file.readline()
        # Process the line here

This is a very common technique to use range to control the number of loops. The only downside is: there's an unused i variable.

Is this the best I can get from Python? Any better ideas?

P.S. In Ruby we can do:

3.times do
  puts "This will be printed 3 times"
end

Which is elegant and express the intention very clearly.

yegle
  • 5,795
  • 6
  • 39
  • 61
  • One of the reasons Python lacks that feature is that when you write testable code, it is actually pretty rare to want to do the thing you're asking about. Sure, it happens, but not as much as all the other loops being written. – kqr Oct 16 '13 at 05:29
  • FYI, change your Ruby to `3.times do |x|` and `x` is now equivalent to `i` in your Python example. Like @poundifdef said, Ruby is just hiding it from you. – sberry Oct 16 '13 at 05:30

4 Answers4

11

That's pretty much the best option for looping over something a specific amount of times.

A common idiom is to do for _ in ... instead, representing the _ as a sort of placeholder.

TerryA
  • 58,805
  • 11
  • 114
  • 143
5

Use islice from itertools

from itertools import islice
with open("input", 'r') as input_file:
    for line in islice(input_file, 10):
        #process line

Since you can iterate over lines of files directly, there is no need to call input_file.readline() see the documentation for itertools.islice

JaminSore
  • 3,758
  • 1
  • 25
  • 21
1

There is no equivalent construct in python.

(Incidentally, even in the Ruby example, there is still a need for a counter! The language simply hides it from you. It is also possible that the interpreter is generating bytecode with those lines repeated multiple times, rather than a loop, but that is unlikely.)

poundifdef
  • 18,726
  • 23
  • 95
  • 134
0

The solution you already provided is pretty much the best one.

However, if you really wanted to, you could abstract it out using generators and iterslice so you don't need to see an unused variable:

import itertools

def take(iterable, amount):
    return itertools.islice(iterable, 0, amount)

with open("inputfile.txt") as file:
    for line in take(file.readlines(), 3):
        print line
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • For looping over an iterable, `itertools.islice` is the best solution, thank you for sharing. – yegle Oct 16 '13 at 18:10