如何在python中将数组保存到文本文件?

时间:2018-08-15 14:31:06

标签: python

我有一个这种类型的数组:

xyz = [['nameserver','panel'], ['nameserver','panel']]

如何将其保存为以下格式的abc.txt文件:

nameserver panel
nameserver panel

我在遍历每一行时尝试使用此方法:

np.savetxt("some_i.txt",xyz[i],delimiter=',');

显示此错误:

TypeError: Mismatch between array dtype ('<U11') and format specifier 
('%.18e')

5 个答案:

答案 0 :(得分:3)

这是一个可能的解决方案:

data = [['nameservers','panel'], ['nameservers','panel']]

with open("output.txt", "w") as txt_file:
    for line in data:
        txt_file.write(" ".join(line) + "\n") # works with any number of elements in a line

答案 1 :(得分:2)

众多可能性之一:

stuff = [['nameservers','panel'], ['nameservers','panel']]
with open("/tmp/out.txt", "w") as o:
    for line in stuff:
        print("{} {}".format(line[0], line[1]), file=o)

答案 2 :(得分:0)

您可以直接将其写到文件中。

with open('outfile.txt', 'w') as f:
    f.write('\n'.join([' '.join(l2) for l2 in l1]))

其中l1是您提供的列表。

答案 3 :(得分:0)

使用=LEFT(B1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},B1&"0123456789"))-1)

csv.writer

data = [['nameservers','panel'], ['nameservers','panel']] with open('tmp_file.txt', 'w') as f: csv.writer(f, delimiter=' ').writerows(data) 现在想要这个

tmp_file.txt

答案 4 :(得分:0)

可能最简单的方法是使用json模块,然后一步将数组转换为列表:

import json

with open('output.txt', 'w') as filehandle:
json.dump(array.toList(), filehandle)

使用json格式可以实现许多不同系统之间的互操作性。