[英]Loadfile, specific lines from .txt file into array
I have a .txt file and I need to open it and create an array (in Python). 我有一个.txt文件,我需要打开它并创建一个数组(在Python中)。 However, I do not want to select all the lines for the array, everything but the first line.
但是,我不想选择数组的所有行,除了第一行以外的所有行。
For example, my .txt file reads: 例如,我的.txt文件显示为:
1 1 1
1 4 6
4 5 6
8 9 7
and, I would like to create an array such that, I can assign it like: 并且,我想创建一个数组,这样我就可以像这样分配它:
Y= array([[1, 4, 6], [4, 5, 6], [8, 9, 7]])
I need to generalize it for future files that will create an array that omits first line of text. 我需要对将来的文件进行概括,以创建一个省略文本第一行的数组。
You could do 你可以做
with open(file) as f:
Y = [map(int, line.split()) for line in f.readlines()[1:]]
Notice the [1:]
which grabs all the other lines except for the first one. 注意
[1:]
抓住了除第一行以外的所有其他行。
Try: 尝试:
import numpy
data = numpy.loadtxt('data.txt',skiprows=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.