格式化数组并写入文本文件

时间:2015-11-25 15:02:03

标签: python python-2.7

我是python的新手,我需要一个关于格式化数组并将其存储在文件中的帮助。

我有一个数组说

a = [['C', [0.99813803, -0.00263872, -0.00464602]], ['H', [2.0944175, -0.00242373, 0.00417336]], ['H', [0.63238996, 1.03082951, 0.00417296]], ['H', [0.62561232, -0.52974905, 0.88151021]], ['H', [0.64010219, -0.50924801, -0.90858051]]]

现在我想以下列方式将其存储在文件中

C   0.99813803 -0.00263872 -0.00464602
H   2.0944175 -0.00242373 0.00417336 
H   0.63238996 1.03082951 0.00417296 
H   0.62561232 -0.52974905 0.88151021
H   0.64010219 -0.50924801 -0.90858051

我尝试了numpy.savetxt,但它以数组格式存储。我知道,正则表达式我可以删除所有特殊字符,但对我来说问题只在于从数组中逐行写入。

有人能告诉我而不是numpy.savetxt我还能尝试什么吗?

2 个答案:

答案 0 :(得分:1)

a = [['C', [0.99813803, -0.00263872, -0.00464602]], ['H', [2.0944175, -0.00242373, 0.00417336]], ['H', [0.63238996, 1.03082951, 0.00417296]], ['H', [0.62561232, -0.52974905, 0.88151021]], ['H', [0.64010219, -0.50924801, -0.90858051]]]

with open('file.txt', 'w') as f:
for item, values in a:
    line = "{}   {} {} {}\n".format(item, *values)
    f.write(line)

文件内容(输出):

C   0.99813803 -0.00263872 -0.00464602
H   2.0944175 -0.00242373 0.00417336
H   0.63238996 1.03082951 0.00417296
H   0.62561232 -0.52974905 0.88151021
H   0.64010219 -0.50924801 -0.90858051

答案 1 :(得分:1)

您似乎正在尝试编写tsv或csv文件,其中分隔符是制表符或空格。那么为什么不使用csv模块

import csv
from itertools import chain

a = [['C', [0.99813803, -0.00263872, -0.00464602]], ['H', [2.0944175, -0.00242373, 0.00417336]], ['H', [0.63238996, 1.03082951, 0.00417296]], ['H', [0.62561232, -0.52974905, 0.88151021]], ['H', [0.64010219, -0.50924801, -0.90858051]]]
with open('filename', 'w') as f:
    writer = csv.writer(f, delimiter='\t', dialect='excel-tab')
    writer.writerows([list(chain.from_iterable(i)) for i in a])

然后您的文件内容如下所示:

C    0.99813803    -0.00263872    -0.00464602
H    2.0944175    -0.00242373    0.00417336
H    0.63238996    1.03082951    0.00417296
H    0.62561232    -0.52974905    0.88151021
H    0.64010219    -0.50924801    -0.90858051