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.
Asked
Active
Viewed 1,076 times
-3

martineau
- 119,623
- 25
- 170
- 301

charm kass
- 7
- 1
-
show the code of your iteration and its output – Andersson Jul 01 '15 at 13:22
-
your question is about line, but you tried to get range! so what is the actual problem? – Andersson Jul 01 '15 at 13:23
2 Answers
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
-
-
1This 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
-
1Note 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