0

If we have a txt file like

a
b
c
d

I need a function that helps me to read between line 0 and line 3. Something like

>>> Return between_lines(0,3)
>>> b, c

I can't assign 'readlines()' to a variable because the file have 4000 lines and it's too big

mzvic
  • 28
  • 4

1 Answers1

1

Use the file as an iterator; skip the lines you don't want, then read the number of lines you do want, and then you can return those lines without having to iterate over the rest of the file.

def between_lines(a, b):
    with open("file.txt") as f:
        for _ in range(a+1):
            next(f)
        return [next(f).strip() for _ in range(b-a-1)]

print(between_lines(0, 3))  # ['b', 'c']
Samwise
  • 68,105
  • 3
  • 30
  • 44