2

Lets say you have a python file with 50 lines of code in it, and you want to read a specific range lines into a list. If you want to read ALL the lines in the file, you can just use the code from this answer:

with open('yourfile.py') as f:
    content = f.readlines()

print(content)

But what if you want to read a specific range of lines, like reading line 23-27?

I tried this, but it doesn't work:

f.readlines(23:27)
lespaul
  • 477
  • 2
  • 8
  • 21

3 Answers3

6

You were close. readlines returns a list and you can slice that, but it's invalid syntax to try and pass the slice directly in the function call.

f.readlines()[23:27]

If the file is very large, avoid the memory overhead of reading the entire file:

start, stop = 23, 27
for i in range(start):
    next(f)
content = []
for i in range(stop-start):
    content.append(next(f))
wim
  • 338,267
  • 99
  • 616
  • 750
  • In my opinion, when one says "I want line 23 to 27", the latter is included. So, the stop should be the stopping point you actually want... +1. – IMCoins Aug 27 '18 at 23:35
0

Try this:

sublines = content[23:27]
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
0

If there are lots and lots of lines in your file, I believe you should consider using f.readline() (without an s) 27 times, and only save your lines starting wherever you want. :)

Else, the other ones solution is what I would have done too (meaning : f.readlines()[23:28]. 28, because as far as I remember, outer range is excluded.

IMCoins
  • 3,149
  • 1
  • 10
  • 25