Python:将两个列表写入两个列文本文件中

Art*_*nte 18 file list python-3.x

假设我有两个列表:a = [1,2,3] b = [4,5,6]我想将它们写入文本文件,以便获得两列文本文件:

1 4
2 5
3 6
Run Code Online (Sandbox Code Playgroud)

Bur*_*lid 21

只需zip列表,并将其写入csv文件,并使用制表符作为分隔符:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> import csv
>>> with open('text.csv', 'w') as f:
...    writer = csv.writer(f, delimiter='\t')
...    writer.writerows(zip(a,b))
...
>>> quit()
$ cat text.csv
1       4
2       5
3       6
Run Code Online (Sandbox Code Playgroud)


Fab*_*bio 15

您可以使用numpy.savetxt(),它是numpy库中的一个方便工具.一个最小的例子如下:

import numpy as np

xarray = np.array([0,1,2,3,4,5])
yarray = np.array([0,10,20,30,40,50])
#here is your data, in two numpy arrays

data = np.array([xarray, yarray])
data = data.T
#here you transpose your data, so to have it in two columns

datafile_path = "/your/data/output/directory/datafile.txt"
with open(datafile_path, 'w+') as datafile_id:
#here you open the ascii file

    np.savetxt(datafile_id, data, fmt=['%d','%d'])
    #here the ascii file is written. 
Run Code Online (Sandbox Code Playgroud)

open()命令中"w +"中的"+"表示"如果不存在则创建"

示例中np.savetxt()中的fmt字段指定数字是整数.您可以为每列使用不同的格式.例如,要指定浮点格式,使用2位十进制数字'%.2f'.


Sye*_*idi 5

尝试这个:

file = open("list.txt", "w")
for index in range(len(a)):
    file.write(str(a[index]) + " " + str(b[index]) + "\n")
file.close()
Run Code Online (Sandbox Code Playgroud)