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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51860716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:57:14  来源:igfitidea点击:

How save a array to text file in python?

python

提问by sarpit23

I have a array of this type:

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

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

How can I save this to an abc.txt file in this format:

如何以这种格式将其保存到 abc.txt 文件中:

nameserver panel
nameserver panel

I tried this using, on iterating over each row:

我在迭代每一行时尝试使用:

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

It's showing this error:

它显示此错误:

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

回答by ybl

This is a possible solution:

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

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

回答by ybl

One of many possibilities:

许多可能性之一:

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)

回答by Agile Bean

Probably the simplest method is to use the json module, and convert the array to list in one step:

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

import json

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

Using the json format allows interoperability between many different systems.

使用 json 格式允许许多不同系统之间的互操作性。

回答by Sunitha

Use csv.writer

csv.writer

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

with open('tmp_file.txt', 'w') as f:
    csv.writer(f, delimiter=' ').writerows(data)

tmp_file.txtwould now like this

tmp_file.txt现在想要这个

nameservers panel
nameservers panel

回答by modesitt

You can just write it out to a file directly.

您可以直接将其写入文件。

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

where l1is the list you gave.

l1你给的清单在哪里。