从.dat文件中读取数据到python

时间:2015-12-12 10:47:06

标签: python variables input

我有一个 file.dat ,如下所示:

0.00000000000000000000 0.00000000000000000000 0.00000000000000000000
1.02072021799999990144 0.58931309249999996869 0.01464322176999999919
1.04801084399999999697 0.60506934300000003724 0.02121744689000000170
1.11938267900000010258 0.64627589110000005501 0.03132390833999999791
1.23483727700000001093 0.71293363409999999103 0.03462252470999999804
1.36316318200000008432 0.78702263009999995358 0.02774525518999999829
1.44821317199999999303 0.83612626459999994655 0.01540671738000000054

我想创建3个变量 x,y,z ,这样 x 就是一个带有第一列的数组, y 第二列, z ,第三列。我试过以下内容:

with open('filename') as f:
     file = f.read()

     x = [row.split(' ')[0] for row in data]
     y = [row.split(' ')[1] for row in data]
     z = [row.split(' ')[2] for row in data]

但是,这不起作用,它会出错。有没有简单易行的方法来执行此操作?

3 个答案:

答案 0 :(得分:2)

  1. f.read()返回整个文件。我认为你需要拆分它们,使用str.splitlines()

  2. file = f.read()for row in data?我认为你的意思是data = f.read()

  3. 如果您正在寻找更简单的方法,我建议:

    with open('filename') as f:
        data = f.read().splitlines()
        x, y, z = zip(*[i.split() for i in data])
    

    或者只是不定义data变量:

    with open('filename') as f:
        x, y, z = zip(*[line.split() for line in f])
    

    这给了你:

    >>> print(x)
    ('0.00000000000000000000', '1.02072021799999990144', '1.04801084399999999697', '1.11938267900000010258', '1.23483727700000001093', '1.36316318200000008432', '1.44821317199999999303')
    >>> print(y)
    ('0.00000000000000000000', '0.58931309249999996869', '0.60506934300000003724', '0.64627589110000005501', '0.71293363409999999103', '0.78702263009999995358', '0.83612626459999994655')
    >>> print(z)
    ('0.00000000000000000000', '0.01464322176999999919', '0.02121744689000000170', '0.03132390833999999791', '0.03462252470999999804', '0.02774525518999999829', '0.01540671738000000054')
    >>> 
    

答案 1 :(得分:2)

首先,您可以使用numpy.genfromtxt将文本作为数组读取,然后通过转置数组来获取列:

import numpy as np

with open('text.dat') as f:
    array = np.genfromtxt(f)
    x,y,z = array.T

关于你的代码,不清楚是什么data,无论如何你想循环遍历文件行,你需要简单地循环文件对象:

x = []
y = []
z = []
with open('filename') as f:
    for line in f:
     i,j,k = line.split()
        x .append(i)
        y .append(j)
        z .append(k)

或者以更优雅的方式使用zip()函数来获取列:

with open('text.dat') as f:
     x, y, z = zip(*[line.split() for line in f])

答案 2 :(得分:1)

试试这个。行中的split()并将其附加到列表中,类似这样。虽然很简单

x=[]
y=[]
z=[]
with open('file.txt') as handler:
    for line in handler:
        parts = line.split()
        x.append(parts[0]) 
        y.append(parts[1])
        z.append(parts[2]) 
print x,y,z

x yz分别包含第一行和第三行