简体   繁体   中英

save output values in txt file in columns python

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,3 is 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

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM