python输出到一个文本文件 [英] python output to a text file
问题描述
我需要将我从我的代码计算的值输出到某种格式的文本文件中。首先,我将解释如何从Python代码的输出,然后解释我希望文本文件。
$ b $ pre $ 列A
1
2
3
4
列B
3
4
1
9
列C
20
56
89
54
<
数字列A列B列C
0 1 3 20
1 2 4 56
2 3 1 89
3 4 9 54
屏幕上的所有输出都是由于使用代码计算的变量值的打印语句。你可以帮助我如何做到这一点?
如果项目顺序,你将不得不保存到列表,字典或其他东西,然后打印。看看这个例子:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $输出= [[]为我在范围(5)]#[[],[], ([A列,1,2,3,4])的$:
:
$ print(item)
output [ind] .append(item)
for ind,item in enumerate([Column B,3,4,1 (output.txt,w)
print(item)
output [ind] .append(item)
作为f:
输出中的行:
f.write('\t'.join(row))
f.write('\\\
')
$ b
打印:列A
1
2
3
4
列B
3
4
1
9
输出:
[['列A','列B'],['1','3'],['2','4'],['3','1'],['4' ,'9']]
output.txt:
A列B
1 3
2 4
3 1
4 9
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
这篇关于python输出到一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!