在使用Python读取文件时跳过行并将行保存到多个数组中

1 投票
1 回答
666 浏览
提问于 2025-04-18 01:21

我有一个样本文件 test.dat,里面保存了以下数据:

n x   y   z   c   i1    i2
------------------------------------
1 1.2 3.4 5.6 1.0 111.1 222.2 
2 7.8 9.0 1.2 2.0 333.3 444.4  
3 3.4 5.6 7.8 1.0 555.5 666.6
------------------------------------
I do not need the last line. 

我想做以下几步:

  • 打开这个文件并读取内容。
  • 跳过前两行。
  • 把前四列的数据保存到一个数组 dist 中,把第五列的数据保存到另一个数组 c 中,最后两列的数据就不管它了。
  • 最后两行也要跳过。
  • 打印出数组 distc 的内容。

我目前写了以下代码:

with open('test.dat', 'r') as f:
    dump = f.readline().strip()
    dump = f.readline().strip()
    array = [ [float(x) for x in line.split()] for line in f]
f.closed

请告诉我如何用 Python 和 ndarray 来实现这个,因为我之后还想对数据进行一些数值运算。谢谢!

1 个回答

0

要把整个文件读入一个数组:

out = np.genfromtxt('test.dat', skip_header=2, skip_footer=1, usecols=range(5))

如果想把它分成两个数组:

dist, c = np.split(out, [4], 1)

或者可能更简单的方法是:

dist = out[:, :4]
c = out[:, 4]

撰写回答