Find Dict Key in File Lines and Append Value on Next Line

Viewed 42

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
1 Answers

You need to store the data from the text to a list and then after processing it write that list back to the file

Ex:

file_being_read = "path_to_file"

dict_speciesNAME_dnaSEQ = {'species1':'dna_seq1', 'species2':'dna_seq2', 'species3':'dna_seq3'}

result = []
with open(file_being_read, 'r') as infile:
    for line in infile:
        result.append(line)
        for k,v in dict_speciesNAME_dnaSEQ.items():
            if k in line:
                result.append(v+"\n")

# Write Back to File
with open(file_being_read, 'w') as outfile:
      for line in result:
          outfile.write(line)  
Related