2012-07-21 57 views
1

我是Python的新手,我对此有一个解决方案,但它看起来很慢并且很傻,所以我想知道是否有更好的方法?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数组,因为虽然大多数矩阵由单个字符元素组成,但前几列的长度会很多,看起来好像很多(纠正我,如果我错了)这将意味着整个矩阵会使用更多的内存比必要的,因为矩阵中的每个元素将是最大元素的大小。

+0

内部实现numpy的是比你想象的更聪明。 ;-) – Keith 2012-07-21 05:39:24

回答

2

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

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

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

第一个具有作为发电机的表达,只有使的一个连接字符串复制的优点currentline

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

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

EDIT

看来,file.writelines()方法它写入文件之前评估整个发电机表达。所以下面将最大限度地减少你的内存消耗:

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

这更直截了当。学习学习..谢谢! – explodecomputer 2012-07-23 03:39:23

1

你可以使用csv module

import csv 

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

感谢您的建议,这对我将来会有帮助 – explodecomputer 2012-07-23 03:39:54