Python:将大量数组写入文本文件

时间:2012-07-21 04:54:39

标签: python matrix text-files

我是Python的新手,我有一个解决方案,但它似乎缓慢而愚蠢,所以我想知道是否有更好的方法?

假设我有一个像这样定义的矩阵:

mat = [['hello']*4 for x in xrange(3)]

我正在使用此函数将其写入文件:

def writeMat(mat, outfile):
  with open(outfile, "w") as f:
    for item in mat:
      f.writelines(str(item).replace('[','').replace(',','').replace('\'','').replace(']','\n'))

writeMat(mat, "temp.txt")

,它提供了一个看起来像的文本文件:

hello hello hello hello
hello hello hello hello
hello hello hello hello

我正在处理的文件非常大。 numpy中的savetxt函数会很棒,但我不想将它存储为numpy数组,因为虽然矩阵的大部分由单个字符元素组成,但前几列的长度将是多个字符,在我看来(如果我错了,请纠正我)这意味着整个矩阵将使用比必要更多的内存,因为矩阵中的每个元素都将是最大元素的大小。

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你可以这样做:

f.writelines(' '.join(row) + '\n' for row in mat)

f.write('\n'.join(' '.join(row) for row in mat))

第一个优点是作为生成器表达式,只生成当前行的串联字符串副本

如果你的矩阵条目不是字符串,你可以这样做:

f.writelines(' '.join(str(elem) for elem in row) + '\n' for row in mat)

修改

file.writelines()方法似乎在将整个生成器表达式写入文件之前对其进行计算。因此,以下内容可以最大限度地减少内存消耗:

for row in mat:
    f.write(' '.join(row) + '\n')

答案 1 :(得分:1)

您可以使用csv module

import csv

with open(outfile, 'wb') as f:
     csv.writer(f, delimiter=' ').writerows(mat)