save output values in txt file in columns python

2019-08-03 21:55发布

问题:

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.