tvoirand
tvoirand

Reputation: 430

Stop inferior to start in python range

I would like to read values from a text file if the file contains text after a given line start_line.

I am importing the file with this method:

with open("filename", "r") as file:
    file_contents = file.readlines()

Would it be a bad practice to then do:

for line in range(start_line, len(file_contents)):
    ... reading contents of line ...

I've noticed that range(start,stop) returns an empty list if start <= stop, and that the for loop is skipped.

Is it uselessly redundant to add before the loop:

if len(file_contents) > start_line:

Upvotes: 0

Views: 243

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 148910

As an old dinosaur used to dealing with scarce resources I do not like to load a whole file in memory when it can be avoided. So I would do:

with open("filename", "r") as file:
    for numline, line in enumerate(file):      # skip up to start_line-1
        if numline == start_line - 1: break
    if num_line == start_line - 1:             # Ok file is long enough
        for line in file:                      # process end of file
            ...

But if you only process small files this would be a useless optimization...

Upvotes: 1

BoarGules
BoarGules

Reputation: 16952

I would avoid using range() like that. You have already read all of the data into file_contents. Unless I have missed something, this

for line in file_contents[start_line:]:
    ... process data in line ...

will do what I think you want.

Upvotes: 1

sophros
sophros

Reputation: 16660

The condition:

if len(file_contents) > start_line:

is de facto logically equivalent to what happens in the loop:

for line in range(start_line, len(file_contents)):
    ... reading contents of line ...

So it would be a duplication of logically equivalent conditions - unnecessary at best.

Upvotes: 1

Related Questions