How to store a file line by line into numpy.ndarray (Python)

Viewed 71

I have to import a file, which for example contains 3 rows of numbers:

1 2 3 4
1 2 3
1 2 3 4 5 6

How can I store them into a numpy.ndarray M, so that for example M[0] gives a np.array containing the first row, i.e. [1,2,3,4]?

Thanks in advance.

2 Answers

How about this:

import numpy as np


with open('test_file.txt') as file:
    arr = np.array(
        [
            np.array([float(num) for num in line.strip().split("\t")])
            for line in file
        ]
    )
print(arr)

and the array should look like the one below:

[array([1., 2., 3., 4.]) array([1., 2., 3.])
 array([1., 2., 3., 4., 5., 6.])]

Same as Giorgios but with a np.array instead of a list for rows :

import numpy as np


with open('test_file.txt') as file:
    arr = np.array(
        [
            np.array([float(num) for num in line.split(" ")])
            for line in file
        ]
    )
print(arr)
Related