Python read text file from second line to fifteenth [closed]
Asked Answered
M

4

19

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!

Mickel answered 24/8, 2013 at 19:9 Comment(0)
B
42

Use itertools.islice:

from itertools import islice
with open('filename') as fin:
    for line in islice(fin, 1, 16):
        print line
Burchell answered 24/8, 2013 at 19:11 Comment(4)
+1 best way to do this.Tenancy
@AshwiniChaudhary Why is it the best way? Because islice uses generator expressions?Desinence
@Desinence 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.Tenancy
+1 This seems very elegant. I wasn't aware of islice before. itertools is quite the treasure chest!Phage
C
9

If the file isn't very big:

with open('/path/to/file') as f:
    print f.readlines()[1:15]
Campo answered 24/8, 2013 at 19:11 Comment(1)
If the file is huge this will load everything into memory.Tenancy
I
5

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

For example:

with open("a.txt", "r") as text_file:
    data = text_file.readlines()

now data[1] will be second line and data[14] will be 15th, so you can slice it as such data[1:14]

Then you can put them into a variable and that's it

Instil answered 24/8, 2013 at 19:14 Comment(1)
Open files in a with block.Brocky
R
4

Jon's answer is definitely a more pythonic and clean approach.


Alternatively, you can use enumerate():

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:

with open("file", 'r') as f:
    for i, x in enumerate(f):
        if 1 <= i <= 15:
            print x
        elif i > 15:
            break
Raja answered 24/8, 2013 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.