从for循环中写出多个文件

时间:2013-06-11 10:38:16

标签: python python-3.x

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

上面的程序将一个由所有结果(50个元素)组成的文件(result.txt)写在一起。

我想写出10个文件,每个文件由5个元素组成,命名如下:

的1.txt

2.txt

...

10.txt

1.txt文件将总和为1 + 11,1 + 12,1 + 13,1 + 14和1 + 15.

2.txt文件将总和为2 + 11,2 + 12,2 + 13,2 + 14和2 + 15.

.....

10.txt文件将总和10 + 11,10 + 12,10 + 13,10 + 14和10 + 15。

请帮忙。预计会有非常简单的程序。

同样,当我想使用N的元素命名out文件时,为什么我不能?

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 个答案:

答案 0 :(得分: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

<强>更新

您可以在此处使用zip()zip从传递给它的序列返回相同索引上的项目。

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

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.

答案 1 :(得分: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)

答案 2 :(得分: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))