问题描述
我正在尝试编写一个 Python 脚本来创建一个多行文件,其中包含一个标题和存储在列中的值。我对 Python 很陌生,所以某处可能有一个愚蠢的错误,但我已经尝试了很多东西,在互联网上查看但我找不到如何解决我的问题...
import csv
A=[1,2]
B=[1.5,0.5]
C=[2.5,3]
with open('test.txt','w',newline='',encoding='utf-8') as f:
writer = csv.writer(f,delimiter='\t')
writer.writerows(zip("TestA","TestB","TestC"))
writer.writerows(zip(A,B,C))
我期待类似的东西:
TestA TestB TestC
1 1.5 2.5
2 0.5 3
但我明白了:
T T T
e e e
s s s
t t t
A B C
1 1.5 2.5
2 0.5 3
有没有人想得到我想要的东西? 谢谢!
解决方法
没有办法使用 writer.writerows()
进行水平写入,而不必进行一些复杂的列表转置。相反,为什么不像这样使用 File write()
:
A=[1,2]
B=[1.5,0.5]
C=[2.5,3]
with open('test.txt','w',newline='',encoding='utf-8') as f:
f.write('TestA\tTestB\tTestC\n')
for i in range(2):
f.write(str(A[i]) + "\t")
f.write(str(B[i]) + "\t")
f.write(str(C[i]) + "\t\n")
产生:
TestA TestB TestC
1 1.5 2.5
2 0.5 3
这是另一个应该有用的链接:Correct way to write line to file?