I have a dictionary made of keys and values. The keys correspond to a species name, and the values correspond to a DNA sequence. I am wanting to read the lines of another file, and when a key from my dictionary is found, append its value on the next line in the file.
The issue I am running into is that all of my values are appending to the bottom of the file. This seems as if it should be a very simple thing to do, but I cannot figure out how to do it.
I have searched SO for a solution with no luck, so I appreciate any help that may be given.
Here is an example of the code I am using:
#!/usr/bin/env python3
import os
file_being_read = "path_to_file"
dict_speciesNAME_dnaSEQ = {'species1':'dna_seq1', 'species2':'dna_seq2', 'species3':'dna_seq3'}
for lines in open(file_being_read, 'r'):
for k,v in dict_speciesNAME_dnaSEQ.items():
with open(file_being_read, 'a') as outfile:
if k in lines:
outfile.write(v)
Lines of file_being_read:
>Seq1 species1
>Seq2 species3
>Seq3 species2
Output from my code:
>Seq1 species1
>Seq2 species3
>Seq3 species2
dna_seq1
dna_seq3
dna_seq2
Desired output:
>Seq1 species1
dna_seq1
>Seq2 species3
dna_seq3
>Seq3 species2
dna_seq2