0

The way to grab the first 10 lines of a text file could be done this way:

with open("myfile.txt") as myfile:
        lines = [next(myfile).strip() for x in xrange(10)]

This will print the first 10 lines

But what if I only wanted lines 5-10? How would I do that? The file isn't small, it's going to be big. I need an efficient way to do this.

Thank you.

user3196332
  • 361
  • 2
  • 4
  • 11
  • 2
    possible duplicate of [How to read file N lines at a time in Python?](http://stackoverflow.com/questions/5832856/how-to-read-file-n-lines-at-a-time-in-python) – Oleg Jul 21 '14 at 02:27
  • Yep, the `islice` solution from that question is the way to go, imo: `lines = [line.strip() for line in islice(myfile, 5, 11)]` – dano Jul 21 '14 at 02:29

5 Answers5

1

By far the easiest way to do this is with itertools.islice:

with open('myfile.text') as f:
    lines = islice(f, 5, 11)

The nice part about this is that it won't ever load the entire file; it'll do only as much work as it needs to.

Note that the functions in itertools are lazy, so you need to either finish working with the lines before you close the file, or wrap the islice in a list() to force evaluation.

Eevee
  • 47,412
  • 11
  • 95
  • 127
0

How about slicing the list that you already have.

with open("myfile.txt") as myfile:
    lines = [next(myfile).strip() for x in xrange(10)][5:10]
Andrew Johnson
  • 3,078
  • 1
  • 18
  • 24
0

If you know where you want to start just change the range in the for loop for example.

var1 = 5
var2 = 10
for x in range(var1, var2):

would loop from 5 to 10, of course you can tweak your variables further.

Donkyhotay
  • 73
  • 6
0

I'd do something like this:

>>> with open("myfile.txt") as myfile:
>>>  lines = myfile.read().split('\n')[5:10]

Split will separate it line by line into an array of lines, and the [5:10] will return array elements from 5 to 10, the variable "lines" will be an array, however, so to just get a string of lines 5 to 10, you could:

>>> with open("myfile.txt") as myfile:
>>>  lines = '\n'.join(myfile.read().split('\n')[5:10])

The only difference here, is the '\n'.join() part, which just takes each element of the array of lines, and joins them into a string seperated by a newline.

0

Reads the file and takes lines x to y as a list to content variable:

with open('content.txt') as f:
    content=f.read().split('\n')[x-1:y]

Take care of '\n' and '\r\n'.

Yogeesh Seralathan
  • 1,396
  • 4
  • 15
  • 22