我想将test.py的整个输出保存在一个数组中。我该怎么办?
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)
输出:
['1.0' '0.0' '3.0']
['2.0' '0.5' '0.0']
打印出循环:
print(t)
超出循环的输出:
['2.0' '0.5' '0.0']
如何获得这样的东西?
[['1.0' '0.0' '3.0']
['2.0' '0.5' '0.0']]
import numpy as np
a = [0,1]
d = []
with open('test.txt') as fd:
for n, line in enumerate(fd):
if n in a:
t = d.append(line.split())
print(t)
np.asarray(d)
您的问题的答案发布在以下帖子中:How to read a file line-by-line into a list?
总结来自@SilentGhost的解决方案,以您的代码:
with open('test.txt') as fd:
t = fd.readlines()
t = [x.strip() for x in t]