繁体   English   中英

从for循环中写出多个文件

[英]writing multiple out files from for loop

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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