Reputation: 183
I have searched the page for an answer but could only find similar topics that don't exactly touch my specific question. I'm trying to generate some Dna sequences to play around with biopython and to write all of them into a txt.file.
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)
However, this obviously only writes the last line into the file. How can I write all the lines into a file (line by line if necessary) or how can I change the dequence generation code in order to be able to do so?
greetings, bert
Upvotes: 0
Views: 216
Reputation: 113965
You're super close!
You just have to move your for loop within the with block:
with open('dna.txt', 'w+') as output:
for _ in range(15):
dna = random_dna_sequence(30)
output.write(dna)
Upvotes: 3