If I'm reading this correctly, this function should only read the rows which are numbered in the range [start_line, end_line]
(I'm assuming this is an inclusive range, i.e. you want to read both the start and end lines as well). Why not write your for loop with enumeration and simply skip rows that are out of the passed range?
def read_line_range_inclusive(start_line, end_line):
filename = "data.txt"
with open(filename) as f:
for i, line in enumerate(f):
if i < start_line: # will read the start line itself
continue # keep going...
if i > end_line: # will read the end line itself
break # we're done
# ... perform operations on lines ...
Also, be careful when splitting by commas; this works fine for simple rows like 1,2,3
but what about 1,2,"a,b,c",3
, where "abc"
shouldn't be split into separate columns? I recommend using the built-in csv module, which handles these edge cases automatically:
import csv
def read_line_range_inclusive(start_line, end_line):
filename = "data.txt"
with open(filename) as f:
for i, row in enumerate(csv.reader(f)):
# row will already be separated into list
# ... proceed as before ...
Note that you can only use the with
statement on the file object itself, not on the csv.reader parsed file, so this wouldn't work: with csv.reader(open(filename)) as f:
.