[英]python: rows from a textfile
I want to save the whole output of test.py in an array.我想将 test.py 的整个输出保存在一个数组中。 How can I do this?
我怎样才能做到这一点?
test.txt测试.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']]
If you don't know the size ahead of time, you can append to a list instead, then convert to numpy array.如果您事先不知道大小,则可以改为附加到列表,然后转换为 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:
d.append(line.split())
np.asarray(d)
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:总结@SilentGhost 为您的代码提供的解决方案:
with open('test.txt') as fd:
t = fd.readlines()
t = [x.strip() for x in t]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.