0

I want to save the whole output of test.py in an array. How can I do this?

test.txt

1.0  0.0  3.0
2.0  0.5  0.0

6.0  4.0  2.0
1.0  0.0  3.0

test.py

a = [0,1]

with open('test.txt') as fd:
    for n, line in enumerate(fd):
        if n in a:
            t = numpy.array(line.split())
            print(t)

Output:

['1.0' '0.0' '3.0']
['2.0' '0.5' '0.0']

print beyond the loop:

print(t)

Output beyond the loop:

['2.0' '0.5' '0.0']

How can I get something like this?

[['1.0' '0.0' '3.0']
['2.0' '0.5' '0.0']]
Jolosin
  • 33
  • 1
  • 6

2 Answers2

0

If you don't know the size ahead of time, you can append to a list instead, then convert to numpy array.

import numpy as np
a = [0,1]
d = []
with open('test.txt') as fd:
    for n, line in enumerate(fd):
        if n in a:
            d.append(line.split())

np.asarray(d)
001001
  • 530
  • 1
  • 4
  • 13
0

The answer for your question is published in the following post: How to read a file line-by-line into a list?

Summing up the solution from @SilentGhost for your code:

with open('test.txt') as fd:
    t = fd.readlines()
t = [x.strip() for x in t] 
Dharman
  • 30,962
  • 25
  • 85
  • 135