[英]Python - reading data from file
I am quite new with Python, and I am having some problems trying to read data from a file. 我是Python的新手,尝试读取文件中的数据时遇到了一些问题。 This is how the file looks like:
文件是这样的:
3.25 5.82 3.29 5.81 2.11 3.59
3.23 5.79 3.22 5.76 2.06 3.58
3.26 5.80 3.25 5.80 2.06 3.61
3.22 5.81 3.22 5.84 2.07 3.65
3.31 5.91 3.32 5.90 2.09 3.67
3.31 5.91 3.32 5.90 2.09 3.67
And this is the part of the code I am using to read that: 这是我用来阅读的代码的一部分:
with open("list_spectral_ron.txt") as ron_list:
for line in ron_list.readlines():
if (line[0] != '\n') & (line[0] != '#'):
line_split = line.split()
I want to save this data in an array, so I can access one entire row or column (I want to plot this data after). 我想将此数据保存在一个数组中,所以我可以访问整个整行或整列(我想在其后绘制该数据)。 The problem is that "line.split()" gives me a column vector each time he reads the line and I don't know how to "concatenate" all the lines to form a 2D array.
问题是,“ line.split()”每次读取行时都会给我一个列向量,而我不知道如何“连接”所有行以形成2D数组。 I always obtain a vector like this:
我总是得到这样的向量:
3.25 5.82 3.29 5.81 2.11 3.59 3.23 5.79 3.22 5.76 2.06 3.58 ... and so on
instead of a 2D array. 而不是2D阵列。
I tried with append and concatenate functions, but I achieve nothing. 我尝试了追加和串联功能,但没有实现。 How could I save the data as a 2D array??
如何将数据另存为2D数组?
file = open("list_spectral_ron.txt", "r")
array_2d = []
for line in file:
array_2d.append(line.strip().split(' '))
file.close()
Try modifying the split function argument: 尝试修改split函数参数:
line_split = line.split(' ')
Now you should get an array [3.25, 5.82 ... ] for each line 现在您应该为每行获得一个数组[3.25,5.82 ...]
Then just add the line_split array to a total array which you defined outside of the loop 然后只需将line_split数组添加到循环外定义的总数组中
total_array.append(line_split)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.