Take the 2-minute tour ×

I have a text file and I need to read from the seconds line to to 15th line including. I've tried some methods but no method worked for me... I'd be happy if anyone could help me ... thanks a lot!

share|improve this question

closed as off-topic by KillianDS, phimuemue, chrylis, iCodez, Antti Haapala Aug 25 '13 at 0:19


  • "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist" – phimuemue, chrylis, iCodez, Antti Haapala

add comment

4 Answers

up vote 2 down vote accepted
with open("file", 'r') as f:
    print [x for i, x in enumerate(f) if 1 <= i <= 15]

Note, that this will loop over all lines in a file. It's better to break the loop after the 15th line, like this:

    for i, x in enumerate(f):
        if 1 <= i <= 15:
            print x
        elif i > 15:
share|improve this answer
add comment

Use itertools.islice:

from itertools import islice
with open('filename') as fin:
    for line in islice(fin, 1, 16):
        print line
share|improve this answer
+1 best way to do this. –  undefined is not a function Aug 24 '13 at 19:15
@AshwiniChaudhary Why is it the best way? Because islice uses generator expressions? –  thefourtheye Aug 24 '13 at 19:31
@thefourtheye islice is a fast and pythonic way to get a slice from an iterator, It does loops over the iterator but that happens internally at C speed. –  undefined is not a function Aug 24 '13 at 19:49
@AshwiniChaudhary Thanks :) –  thefourtheye Aug 24 '13 at 19:54
+1 This seems very elegant. I wasn't aware of islice before. itertools is quite the treasure chest! –  Frerich Raabe Feb 18 at 21:11
add comment

I think you can just read the lines and take the ones you need

For example:

file = open("a.txt", "r")
data = file.readlines()

now data[1] will be second line and data[14] will be 15th

You can put them into a variable and that's it

share|improve this answer
Open files in a with block. –  Aleksander Lidtke Aug 24 '13 at 19:31
add comment

If the file isn't very big:

with open('/path/to/file') as f:
    print f.readlines()[1:15]
share|improve this answer
If the file is huge this will load everything into memory. –  undefined is not a function Aug 24 '13 at 19:17
add comment
