Python:将数组转换为文本文件

2024-03-29 09:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我处理的数据格式如下:

x = [1,2,3,4,5,6]

等等。我怎样才能把这个列表转换成一个.txt文件呢?你知道吗


Tags: 文件txt列表数据格式
3条回答

在python中,可以使用write命令写入文件。write()将字符串的内容写入缓冲区。不要忘记使用close()函数关闭文件。你知道吗

data = [1,2,3,4,5,6]

out = open("output.txt", "w")

for i in data:
    out.write(str(i) + "\n")

out.close()
with open(r'C:\txtfile\exported_array.txt', 'w+') as txt_export:
    for i in x: txt_export.writelines(str(i))

123456保存到txt中

with open(r'C:\txtfile\exported_array.txt', 'w+') as txt_export:
    for i in x: txt_export.writelines(str(i)+',')

1,2,3,4,5,6,保存到txt中

with open(r'C:\txtfile\exported_array.txt', 'w+') as txt_export:
    for i in x: txt_export.writelines(str(i)+'\n')

将保存

1
2
3
4
5
6

转换为txt

Python2.7,要在每行生成一个数字:

with open('list.txt', 'w') as f:
    print >> f, '\n'.join(str(xi) for xi in x)

您可以使用任何其他连接字符串,如','来生成在一行中以逗号分隔的数字。你知道吗

相关问题 更多 >