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

4
  • Split lines on space? Commented Oct 6, 2015 at 12:25
  • But then I can't set it as a numpy array. Comes up with error: "setting an array element with a sequence" Commented Oct 6, 2015 at 12:27
  • 2
    Your last number line has 3 numbers, the others 2? Do you really want that? Commented Oct 6, 2015 at 16:01
  • by the way, filename shouldn't be between quotes Commented May 29, 2024 at 15:52

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.