-3

How do I access specific lines (ie #10-#20) in a text file? I tried for iteration in range(10,20): but it doesn't work.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

3

You can do this with itertools.islice.

import itertools

with open('test.txt', 'rt') as file:
    lines = list(itertools.islice(file, 10-1, 20))

Whether you should use 10 or 10-1 for the first argument to islice() depends on whether you consider the first line of a file line 0, or line 1. Also note that the strings in lines will each end with a newline character.

martineau
  • 119,623
  • 25
  • 170
  • 301
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • One of these days I'll get in the habit of using `with` blocks. – Morgan Thrapp Jul 01 '15 at 14:20
  • 1
    This is actually better than the accepted answer to the duplicate question, although [one of the others](http://stackoverflow.com/a/27108718/355230) says essentially the same thing. – martineau Jul 01 '15 at 14:23
  • @martineau Aw, thanks! :) Yeah, I was flipping through the top answers to the dupe, and I was surprised that none of them suggested islice. – Morgan Thrapp Jul 01 '15 at 14:24
  • Yes it is, especially since `itertools.islice()` has been around since version Python v2.3. – martineau Jul 01 '15 at 14:31
0

I think this is what you want

f = open('file.txt','r')
all_lines = f.readlines()
required_lines = [all_lines[i] for i in range(10,21)]

required_lines will now contain lines from line#10 to line#20

Naman Sogani
  • 943
  • 1
  • 8
  • 28
  • 1
    Note that this will read the whole file; for large files, if you only want ten lines, that's somewhat inefficient. – jonrsharpe Jul 01 '15 at 13:31