python的文件输出,python输出到一个文本文件

I need to output the values that I calculate from my code to a text file in a certain format. First I will explain how my output from the python code look like and then explain how I want the text file to be.

Column A

1

2

3

4

Column B

3

4

1

9

Column C

20

56

89

54

How I want the text file is as below

Number Column A Column B Column C

0 1 3 20

1 2 4 56

2 3 1 89

3 4 9 54

all the output on the screen are due to print statement of variable value that I am calculating using the code. Can you help me on how I can do this?

解决方案

If the items come in that order you will have to save it to a list, dictionary or something and then print. Look at this example:

output = [[] for i in range(5)] # [[],[],[],[],[]]

for ind, item in enumerate(["Column A","1","2","3","4"]):

print(item)

output[ind].append(item)

for ind, item in enumerate(["Column B","3","4","1","9"]):

print(item)

output[ind].append(item)

with open("output.txt", "w") as f:

for row in output:

f.write('\t'.join(row))

f.write('\n')

prints:

Column A

1

2

3

4

Column B

3

4

1

9

Output:

[['Column A', 'Column B'], ['1', '3'], ['2', '4'], ['3', '1'], ['4', '9']]

"output.txt":

Column A Column B

1 3

2 4

3 1

4 9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值