1
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')
3
  • 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 Commented Jun 11, 2013 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? Commented Jun 11, 2013 at 13:03
  • yes, same contents as before Commented Jun 11, 2013 at 13:03

3 Answers 3

2
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.
Sign up to request clarification or add additional context in comments.

12 Comments

@ 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 I've added some explanations, let me know which part you didn't understand.
thank you. i did not catch where did you separate results into ten parts
@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].
@lisa add a print results line before filename line to see what does results contain.
|
1
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)

1 Comment

@AshwiniChaudhary, yes I did :/
0
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))

Comments

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.