save output values in txt file in columns python

独自空忆成欢 提交于 2019-12-13 01:19:31

问题


My input value gives corresponding output values as;

my_list = []
for i in range(1,10):
     system = i,i+2*i
     my_list.append(system)
     print(my_list)

[(1, 3)]

[(1, 3), (2, 6)]

[(1, 3), (2, 6), (3, 9)]

[(1, 3), (2, 6), (3, 9), (4, 12)]

I want output stored in 2 columns; where 1,2,3is first column elements and 3,6,9 for 2nd column.

(1 3)
(2 6)
(3 9)

so on... and then write store these values in text file. For text file, is it possible to generate text file as a part of script? Thanks


回答1:


you need to save the element of my_list that has equal index with i-1 (your range began at 1):

my_list=[] 
with open ('new.txt','w') as f:
 for i in range(1,10):
     system = i,i+2*i
     my_list.append(system)
     print(my_list)
     f.write(str(my_list[i-1])+'\n')

output:

(1, 3)
(2, 6)
(3, 9)
(4, 12)
(5, 15)
(6, 18)
(7, 21)
(8, 24)
(9, 27)

also as says in comments you don't need my_list you can do it with following code :

with open ('new.txt','w') as f:
 for i in range(1,10):
     system = i,i+2*i
     f.write(str(system)+'\n')



回答2:


file = open('out.txt', 'w')
print >> file, 'Filename:', filename  # or file.write('...\n')
file.close()

Basically, look at the "/n" and add it to variable it should append to the next line also:

use ("a" instead of "w") to keep appending to the file. The file will be in the directory you are building from.



来源:https://stackoverflow.com/questions/25967479/save-output-values-in-txt-file-in-columns-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!