-2

I want to extract the first 4 lines from my file into a new string. In this file I have about 400 lines but only need the first 4. I wrote this code with the enumerate() function so I can see the indices of the lines but now I am a little bit confused on how to do the next step.

filename = "data_00-000.raw.seq."

with open(filename, 'r') as fh:
    file_content = fh.read().strip()
    x = file_content.split('\n')

    for value, zeile in enumerate(x, 0):
        print (value, zeile)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
ggg7
  • 1
  • 1

2 Answers2

1

You don't even have to read the entire file:

from itertools import islice

with open(filename, 'r') as fh:
    first4 = list(islice(fh, 4))

islice is a handy util to slice (lazy) iterators in an efficient manner. It will only consume the underlying iterator (here: the file handle) to the point that's needed for the slice. This is roughly equivalent to looping over the enumerated lines and breaking the loop when the index is reached.

user2390182
  • 72,016
  • 6
  • 67
  • 89
-1

You don't need to enumerate it, you can just slice the list:

with open(filename, "r") as f:
    lines = f.readlines()
    for line in lines[:4]: # the [:4] gets the first 4 lines
        print(line)
Aplet123
  • 33,825
  • 1
  • 29
  • 55