Python将两个列表写入一个2列txt文件,重新打开并添加数据,rewri

2024-03-28 08:59:00 发布

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

我有两个几乎100个浮点数值的列表,我需要将它们的数据保存到一个包含两列的txt文件中。但是,我需要这个文件重新打开,添加额外的数据并保存它,至少在我的代码中保存3次。。。如果有人知道。。。


Tags: 文件数据代码txt列表数值浮点
2条回答

你可以试试这个主意:

首先,将两个列表写入两列文本文件。

a=[0.2342,2.0002,0.1901]
b=[0.4245,0.5123,6.1002] 
c = [a, b] 
with open("list1.txt", "w") as file:
    for x in zip(*c):
        file.write("{0}\t{1}\n".format(*x))

其次,重新打开保存的文件list1.txt

with open("list1.txt", "r+") as file:
    d = file.readlines()

第三,添加额外数据

e=[1.2300,0.0002,2.0011]
f=[0.4000,1.1004,0.9802]
g = [e, f]
h = []
for i in d:
    h.append(i)
for x in zip(*g):
    h.append("{0}\t{1}\n".format(*x))

第四,保存文本文件

with open("list2.txt", "w") as file1:
    for x in h:
        file1.writelines(x)

list2.txt文件中的输出如下

0.2342  0.4245
2.0002  0.5123
0.1901  6.1002
1.23    0.4
0.0002  1.1004
2.0011  0.9802

这取决于您希望如何分隔这两列(使用空格、制表符或逗号)。下面是我如何用一个空格作为分隔符快速地完成这项工作:

Python2:

with open('output.txt', 'w') as f:
    for f1, f2 in zip(A, B):
        print >> f, f1, f2

Python3:

with open('output.txt', 'w') as f:
    for f1, f2 in zip(A, B):
        print(f1, f2, file=f)

相关问题 更多 >