1

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

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

with 'system\n' gives me 1 2 3 4 and system system system in 2nd column.
try to add a "+" sign inbetween variable and "/n" so: (variable+ '\n')
2

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

4 Comments

thanks. this saves only one value in out_put file as [(9, 27)].
thanks it works! i was editing my own script. thanks
welcome , so if you fide your answer , you can tell to community with [accepting an answer][1] [1][meta.stackexchange.com/questions/5234/…
@Kasra : Why not f.write(str(system) + '\n') instead of f.write(str(my_list[i-1])+'\n') ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.