从.txt中读取3列数据到列表中

时间:2016-09-28 15:59:47

标签: python list text-files multiple-columns

你好,我在这里有一个问题。我有以下文本文件(3列和空格之间)。我想将每一列(tt,ff,ll)插入到它自己的列表中(时间,l,f)。

文字档案:

time: (0.00,1.00,2.003,4.0007 etc...)
l: (656.53,656.53,656.53,656.53 etc..)
f: (...)

但我想要以下输出:

from numpy import *



def read_file(filename):
   time = [] # list time
   f = [] # ...
   l = [] # ...
   infile = open(filename, "r") # reads file
   for line in infile: # each line in txt file
      numbers = line.split() # removes the " "
      tt = numbers[0] # 1st column?
      ff = numbers[1] # 2nd column?
      ll = numbers[2] # 3rd column?


      time.append(tt) # Inserts 1st column(tt) into list(time) 
      f.append(ff) # ...
      l.append(ll) # ...

return time,f,l # return lists

txt1 =read_file("1.txt") # calls function
print txt1 # print return values

尝试代码:

json()

3 个答案:

答案 0 :(得分:1)

我刚尝试了你的代码并且它可以工作,返回一个列表元组。如果您的问题是如何将这个列表元组转换为您所请求的格式(由于数据量很大,这将非常笨重),您可以使用txt1变量将其添加到最后:

(已编辑以包含换行符)

print ("time: ({})\nl: ({})\nf: ({})".format(*[','.join(i) for i in txt1]))

这用逗号连接每个列表,并使用解包运算符(*)将它们分成format函数的三个参数。

我喜欢使用numpy处理文件功能的其他答案。你也可以使用内置函数这样做(注意这会返回一个元组列表):

def read_file(filename):
  with open(filename, 'r') as f:
    return zip(*[line.split() for line in f])

答案 1 :(得分:0)

使用numpy的loadtxt功能

text_array = np.loadtxt('my_file.txt')
time = text_array[:, 0]
l = text_array[:, 1]
f = text_array[:, 2]

答案 2 :(得分:0)

您的return语句目前未正确缩进。当我纠正它似乎工作。

更简单的方法可能是

def read_file(filename):
    infile = open(filename, "r") # reads file
    rows = [line.split() for line in infile]
    return [r[i] for r in rows for i in range(3)] # return lists