将txt文件导入到浮动列表中

时间:2014-06-02 13:10:06

标签: python file text

我有一个浮点数的txt文件,我想在python脚本中将它打开成2d浮点数列表。如何将txt存储到2d浮点列表?我使用以下代码:

arrays = []
for line in open('normRowsRaw.txt'):
# use a list comprehension to build your array on the fly
      new_array = np.array((array.float(i) for i in line.split(' '))) 
      arrays.append(new_array)

我的文件就像上面的系列一样:

0.0098506, 0.068954, 0.007388, 0.0049253, 0.0049253, 0.054178, 0.014776, 0.014776,  
0.014776, 0.0024627, 0.007388, 0.0098506, 0.007388, 0.022164, 0.029552, 0.017239, 
0.0024627, 0.019701, 0.0098506, 0.0024627, 0, 0.068954, 0.0098506, 0.11082, 0.0024627...

3 个答案:

答案 0 :(得分:2)

您可以使用列表推导将每个字符串转换为float并将2D数组作为numpy数组返回。

import numpy as np
with open('normRowsRaw.txt') as file:
    array2d = np.array([[float(digit) for digit in line.split(",")] for line in file])

答案 1 :(得分:1)

你可以试试这个

arrays = []
with open('normRowsRaw.txt') as f:
    f = f.read().split(',')
    for n in f:
        arrays.append(float(n.strip()))

修改

这会附加到正常列表而不是2d

答案 2 :(得分:0)

这是方法:

for line in open('normRowsRaw.txt'):
    # use a list comprehension to build your array on the fly
    array = line.split(',')
    del array[len(array)-1] #to remove \n from array

    new_array = []
    for i in range(0,len(array)-1):
       new_array.append(float(array[i]))
    #After all elements are added to an array, add array to result
    arrays.append(new_array)