在文本文件中写入多个打印件

Write multiple prints in a text file

我在页面上搜索了答案,但只能找到与我的具体问题不完全相关的类似主题。 我正在尝试生成一些 Dna 序列来玩 biopython 并将它们全部写入 [​​=17=].

import random as r

def random_dna_sequence(length):
     return ''.join(r.choice('ACTG') for _ in range(length))

for _ in range(15):
     dna = random_dna_sequence(30)
     print (dna)

with open('dna.txt', 'w+') as output:
    output.write(dna)

但是,这显然只是将最后一行写入文件。如何将所有行写入文件(如有必要,逐行)或如何更改顺序生成代码以便能够这样做?

问候, 伯特

你非常接近!
您只需在 with 块内移动 for 循环:

with open('dna.txt', 'w+') as output:
    for _ in range(15):
        dna = random_dna_sequence(30)
        output.write(dna)