从 Python 中的 .dat 文件读取特定列

Read specific column from .dat-file in Python

我有一个 results.dat 文件,其中包含如下数据:

7522126 0   0   0   0   0   0   -419.795    -186.24 1852.86 0.134695    -0.995462   -2.53153
7825452 0   0   0   0   0   0   -419.795    -186.24 1852.86 0.134695    -0.995462   -2.53153
8073799 0   0   0   0   0   0   -345.551    -140.711    1819.04 -0.0220266  -0.85992    -2.29598

每个值都用制表符分隔。

我想为每一行提取例如第 8 列中的值,并将其保存到一个数组中。所以输出应该是这样的:

-419.795
-419.795
-345.551

完成此操作的最简单方法是什么?

你可以使用 csv module.

import csv
with open('file') as f:
    reader = csv.reader(f, delimiter="\t")
    for line in reader:
        print(line[7])
with open('results.dat') as f:
    [line.split()[7] for line in f]  

或者定义一个函数,

get_col = lambda col: (line.split('\t')[col-1] for line in open('results.dat'))  

现在调用具有所需列号的函数。 get_col(8) 给出第 8 列数据。要将其存储在数组中,

array.array('d',map(float,get_col(8)))

首先读取文件对象中的文件(result.dat)文件

file = open('result.dat')

现在创建一个空列表

lst = []

遍历文件的每一行

for line in file:
    lst += [line.split()]

现在 lst 是 list 的列表,其中每个内部列表都是 result.dat

的一个实例(行)

现在您可以提取任何列(在您的例子中是第 8 列) 为此应用列表理解

column8 = [x[7] for x in lst]

希望这对您有所帮助,

What's the easiest way to accomplish this?

如果其他答案不符合您的需要,会推荐numpy.genfromtxt

import numpy
data = numpy.genfromtxt('result.dat', delimiter='\t')
print data[:,7]