Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
out_file = open('result.txt', 'w')
A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
for a in A:
    for b in B:
        result = a + b
        print (result, file = out_file)
out_file.close()

The above program writes one out file (result.txt) consisting of all the results (50 elements) together.

I want to write ten out files each consisting of 5 elements and named as follows:

1.txt

2.txt

...

10.txt

The 1.txt file will put the sum of 1+11, 1+12, 1+13, 1+14, and 1+15.

The 2.txt file will put the sum of 2+11, 2+12, 2+13, 2+14, and 2+15.

.....

The 10.txt file will put the sum of 10+11, 10+12, 10+13, 10+14, and 10+15.

Any help, please. Very simple program is expected.

Again, when I wanted to name the out file using elements of N, why I could not?

A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
N = ['a','b','c','d','e','f','g','h','i','j']
for a in A:
    results = []
    for b in B:
        result = a + b
        results.append(result)
        for n in N:
            with open('{}.txt'.format(n),'w') as f:
                for res in results:
                    f.write(str(res)+'\n')
share|improve this question
    
if this is a homework and not the real world use-case (that can be useful for someone else except you) you should at least mark it accordingly. Thnx –  Yauhen Yakimovich Jun 11 '13 at 10:45
    
Instead of names like 1.txt, 2.txt this time you want a.txt, b.txt etc, but same content in the files? –  Ashwini Chaudhary Jun 11 '13 at 13:03
    
yes, same contents as before –  lisa Jun 11 '13 at 13:03

3 Answers 3

up vote 2 down vote accepted
A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
for a in A:
    results = []           # define new list for each item in A
    #loop over B and collect the result in a list(results)
    for b in B:
        result = a + b
        results.append(result)   #append the result to results
    #print results               # uncomment this line to see the content of results
    filename = '{}.txt'.format(a)      #generate file name, based on value of `a`
    #always open file using `with` statement as it automatically closes the file for you
    with open( filename , 'w') as f:
       #now loop over results and write them to the file
       for res in results:
          #we can only write a string to a file, so convert numbers to string using `str()`
          f.write(str(res)+'\n') #'\n' adds a new line

Update:

You can use zip() here. zip return items on the same index from the sequences passed to it.

A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
N = ['a','b','c','d','e','f','g','h','i','j']
for a,name in zip(A,N):
    results = []
    for b in B:
        result = a + b
        results.append(result)
    filename = '{}.txt'.format(name)
    with open( filename , 'w') as f:
       for res in results:
           f.write(str(res)+'\n') 

Help in zip:

>>> print zip.__doc__
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence.
share|improve this answer
    
@ Ashwini Chaudhary thank you for quick response. i accepted your answer because it provided the result i was looking for. unfortunately, i could not understand at all. could you please teach me slowly and simply. –  lisa Jun 11 '13 at 10:45
    
@lisa I've added some explanations, let me know which part you didn't understand. –  Ashwini Chaudhary Jun 11 '13 at 10:49
    
thank you. i did not catch where did you separate results into ten parts –  lisa Jun 11 '13 at 10:56
    
@lisa I am storing the result in results list for each item in A. i.e after first iteration results list is [12, 13, 14, 15, 16]. –  Ashwini Chaudhary Jun 11 '13 at 10:59
    
@lisa add a print results line before filename line to see what does results contain. –  Ashwini Chaudhary Jun 11 '13 at 11:01
A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
for a in A:
    with open(str(a) + '.txt', 'w') as fout:
        fout.write('\n'.join(str(a + b) for b in B)
share|improve this answer
    
@AshwiniChaudhary, yes I did :/ –  John La Rooy Jun 11 '13 at 10:48
A = range(1, 10 + 1)
B = range(11, 15 + 1)

for a in A:
    with open('{}.txt'.format(a), 'wb') as fd:
        for b in B:
            result = a + b
            fd.write('{}\n'.format(result))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.