python:文本文件中的行

问题描述 投票:0回答:1

我想将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']]
python text-files
1个回答
0
投票
如果您不提前知道大小,则可以附加到列表,然后转换为numpy数组。

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)


0
投票
你好吗?

您的问题的答案发布在以下帖子中: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]

© www.soinside.com 2019 - 2024. All rights reserved.