3

I am trying to read a txt file in he format:

[text]
[text]
[text]
1 0 
4 5
3 0 0
[text]
.
.
.

I need to read lines 4 to 6 as a numpy array. So far I've got:

 lines=[]
 with open('filename', "r") as f:
     for i, line in enumerate(f):
         if i>=3 and i<=5:
             lines.append(line)
 lines = np.array(lines)

This reads each of the required lines as an element, but I need to have numbers in separate columns as separate elements. Is there a way around this?

Thanks

rebeling
  • 718
  • 9
  • 31
Afzal
  • 189
  • 3
  • 14

3 Answers3

2

You need to transform string to ints:

lines=[]
with open('filename', "r") as f:
    for i, line in enumerate(x.split('\n')):
        if i>=3 and i<=5:
            lines.append([int(y) for y in line.split()])

lines = np.array(lines)
print type(lines)
rebeling
  • 718
  • 9
  • 31
2

You can use itertools.islice() to select the lines and feed that result to Numpy's genfromtxt() function:

from itertools import islice
import numpy as np

with open('test.txt') as lines:
    array = np.genfromtxt(islice(lines, 3, 6))

print array
BlackJack
  • 4,476
  • 1
  • 20
  • 25
0

You can do this using skiprows and max_rows in numpy.

array = np.loadtxt(filename,skiprows=3,max_rows=3)

max_rows: number of rows you want to read afters skipping skiprows initial rows.

Niladri Gomes
  • 213
  • 1
  • 2
  • 4