我是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数组,因为虽然大多数矩阵由单个字符元素组成,但前几列的长度会很多,看起来好像很多(纠正我,如果我错了)这将意味着整个矩阵会使用更多的内存比必要的,因为矩阵中的每个元素将是最大元素的大小。
内部实现numpy的是比你想象的更聪明。 ;-) – Keith 2012-07-21 05:39:24