Search code examples
pythonsequencebioinformaticsbiopython

python script used to help draw sequences from a separate file


I'm trying to run a python script to draw sequences from a separate file (merged.fas), in respect to a list (gene_fams_eggnog.txt) I have as output from another program.

The code is as follows:

from Bio import SeqIO
import os, sys, re
sequences = "merged.fas"
all_seqs = SeqIO.index(sequences, "fasta")
gene_fams = {}

gene_fams_file = open("gene_fams_eggnog.txt")
for line in gene_fams_file:
   fields = re.split("\t", line.rstrip())
   gene_fams[fields[0]].append[fields[1]]

for fam in gene_fams.keys():
   output_filename = str(fam) + ".fasta"
   outh = open(output_filename, "w")
   for id in gene_fams[fam]:
     if id in all_seqs:
         outh.write(">" + all_seqs[id].description + "\n" + str(all_seqs[id].seq) + "\n")
     else:
        print "Uh oh! Sequence with ID " + str(id) + " is not in the all_seqs file!"
        quit()
     outh.close()

I am however getting an error message:

"File "make_fastafiles_from_gene_family_assignments.py", line 15, in <module>
    gene_fams[fields[0]].append(fields[1])
KeyError: '1'"

It for some reason doesn't recognise the field, but he file certainly has 2 fields (0,1).

The file looks like this:

1   Saccharomycescerevisiae_DAA09367.1

1   bieneu_EED42827.1

1   Asp_XP_749186.1 

1   Mag_XP_003717339.1 

1   Mag_XP_003716586.1 

1   Mag_XP_003709453.1 

1   Asp_XP_749329.1 

(There's no space between the lines, for some reason this website has formatted it like this) Field 0 changes after a time, but that's what the grouping is essentially on.

Any help is appreciated, JT


Solution

  • You need to initialize gene_fams[fields[0]]=[] first and then append to this list gene_fams[fields[0]].append(fields[1]).