Search code examples
pythonpython-3.xnumpyreadlines

Read first N lines using readlines


My python code goes like this

with open('file.txt') as w:
    k = np.asarray(w.readlines(),np.float)

But when I do this k is an array with all lines read from file.txt

I am trying to figure to read only the first n lines and store k using np.asarray How to edit this code with n

Thanks for the help!


Solution

  • from itertools import islice
    with open("file.txt") as myfile:
        k = list(islice(myfile, n))
    print k
    

    or

    with open('file.txt') as w:
        k = np.asarray(w.readlines(),np.float)
        k = k[:,n]