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