繁体   English   中英

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

[英]Python: writing large array of arrays to text file

我是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.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')

你可以使用csv模块

import csv

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM