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

Python:将大型数组写入文本文件,python,matrix,text-files,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('[','').replac

我是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数组,因为虽然矩阵的大部分由单字符元素组成,但前几列的长度将是多个字符,在我看来(如果我错了,请纠正我)这意味着整个矩阵将使用比所需更多的内存,因为矩阵中的每个元素都是最大元素的大小。

如果我正确理解您的问题,您可以:

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

第一个函数的优点是它是一个生成器表达式,只生成currentline的串联字符串副本

如果矩阵项不是字符串,则可以执行以下操作:

f.writelines(' '.join(row) + '\n' 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')
您可以使用:


numpy的内部实现比您想象的更智能。;-)这要简单得多。学习。。谢谢谢谢你的建议,这对我以后会有用的