Answers.Body: <p>One can get it to work by using <a href="http://biopython.org/DIST/docs/api/Bio.SeqIO.InsdcIO-module.html#GenBankCdsFeatureIterator" rel="noreferrer"><code>SeqIO.InsdcIO.GenBankCdsFeatureIterator</code></a>:</p>
  
  <pre><code>from Bio import SeqIO
  
  file_name = 'NC_000913.3.gb'
  
  # stores all the CDS entries
  all_entries = []
  
  with open(file_name, 'r') as GBFile:
  
      GBcds = SeqIO.InsdcIO.GenBankCdsFeatureIterator(GBFile)
  
      for cds in GBcds:
          if cds.seq is not None:
              cds.id = cds.name
              cds.description = ''
              all_entries.append(cds)
  
  
  # write file
  SeqIO.write(all_entries, '{}.fasta'.format(file_name[:-3]), 'fasta')
  </code></pre>
  
  <p>This will then give the desired output (just the first two entries):</p>
  
  <pre><code>&gt;b0001
  MKRISTTITTTITITTGNGAG
  &gt;b0002
  MRVLKFGGTSVANAERFLRVADILESNARQGQVATVLSAPAKITNHLVAMIEKTISGQDA
  LPNISDAERIFAELLTGLAAAQPGFPLAQLKTFVDQEFAQIKHVLHGISLLGQCPDSINA
  ALICRGEKMSIAIMAGVLEARGHNVTVIDPVEKLLAVGHYLESTVDIAESTRRIAASRIP
  ADHMVLMAGFTAGNEKGELVVLGRNGSDYSAAVLAACLRADCCEIWTDVDGVYTCDPRQV
  PDARLLKSMSYQEAMELSYFGAKVLHPRTITPIAQFQIPCLIKNTGNPQAPGTLIGASRD
  EDELPVKGISNLNNMAMFSVSGPGMKGMVGMAARVFAAMSRARISVVLITQSSSEYSISF
  CVPQSDCVRAERAMQEEFYLELKEGLLEPLAVTERLAIISVVGDGMRTLRGISAKFFAAL
  ARANINIVAIAQGSSERSISVVVNNDDATTGVRVTHQMLFNTDQVIEVFVIGVGGVGGAL
  LEQLKRQQSWLKNKHIDLRVCGVANSKALLTNVHGLNLENWQEELAQAKEPFNLGRLIRL
  VKEYHLLNPVIVDCTSSQAVADQYADFLREGFHVVTPNKKANTSSMDYYHQLRYAAEKSR
  RKFLYDTNVGAGLPVIENLQNLLNAGDELMKFSGILSGSLSYIFGKLDEGMSFSEATTLA
  REMGYTEPDPRDDLSGMDVARKLLILARETGRELELADIEIEPVLPAEFNAEGDVAAFMA
  NLSQLDDLFAARVAKARDEGKVLRYVGNIDEDGVCRVKIAEVDGNDPLFKVKNGENALAF
  YSHYYQPLPLVLRGYGAGNDVTAAGVFADLLRTLSWKLGV
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-08-26T08:00:53.707Z
Answers.Text: Is there any way to include the proteins names annotated at the gbk file as the sequence description?
Answers.UserDisplayName: F.Lira
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-05-25T21:07:06.313Z
Answers.LastActivityDate: 2018-05-26T10:16:56.373Z
Answers.LastEditDate: 2018-05-26T10:16:56.373Z
Answers.UserDisplayName: Cleb
Body: <p>Let's say I have a genbank file, e.g. the one downloaded from <a href="https://www.ncbi.nlm.nih.gov/nuccore/NC_000913.3" rel="nofollow noreferrer">here</a>, that contains entries as</p>
  
  <pre><code> gene            190..255
                   /gene="thrL"
                   /locus_tag="b0001"
                   /gene_synonym="ECK0001; JW4367"
                   /db_xref="EcoGene:EG11277"
                   /db_xref="GeneID:944742"
   CDS             190..255
                   /gene="thrL"
                   /locus_tag="b0001"
                   /gene_synonym="ECK0001; JW4367"
                   /function="leader; Amino acid biosynthesis: Threonine"
                   /GO_process="GO:0009088 - threonine biosynthetic process"
                   /codon_start=1
                   /transl_table=11
                   /product="thr operon leader peptide"
                   /protein_id="NP_414542.1"
                   /db_xref="ASAP:ABE-0000006"
                   /db_xref="UniProtKB/Swiss-Prot:P0AD86"
                   /db_xref="EcoGene:EG11277"
                   /db_xref="GeneID:944742"
                   /translation="MKRISTTITTTITITTGNGAG"
  </code></pre>
  
  <p>and I want to extract the potein fasta from it, how would I do this?</p>
  
  <p>I found a code sample <a href="https://warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/genbank2fasta/" rel="nofollow noreferrer">here</a>. When I then run:</p>
  
  <pre><code>from Bio import SeqIO
  
  gbk_filename = 'NC_000913.3.gb'
  faa_filename = 'NC_000913.3_warwick.fasta'
  input_handle  = open(gbk_filename, "r")
  output_handle = open(faa_filename, "w")
  
  for seq_record in SeqIO.parse(input_handle, "genbank") :
      print "Dealing with GenBank record %s" % seq_record.id
      for seq_feature in seq_record.features :
          if seq_feature.type=="CDS" :
              assert len(seq_feature.qualifiers['translation'])==1
              output_handle.write("&gt;%s from %s\n%s\n" % (
                     seq_feature.qualifiers['locus_tag'][0],
                     seq_record.name,
                     seq_feature.qualifiers['translation'][0]))
  
  output_handle.close()
  input_handle.close()
  </code></pre>
  
  <p>it results in </p>
  
  <pre><code>     31     for seq_feature in seq_record.features :
       32         if seq_feature.type=="CDS" :
  ---&gt; 33             assert len(seq_feature.qualifiers['translation'])==1
       34             output_handle.write("&gt;%s from %s\n%s\n" % (
       35                    seq_feature.qualifiers['locus_tag'][0],
  
  KeyError: 'translation'
  </code></pre>
  
  <p>How could this be fixed?</p>
  
Tags: <fasta><python><genbank>
Title: How to extract the protein fasta file from a genbank file?
ThreadText: # How to extract the protein fasta file from a genbank file?
  
  (Asked by: username_0 on 2018-05-25)
  
  Let's say I have a genbank file, e.g. the one downloaded from [here](https://www.ncbi.nlm.nih.gov/nuccore/NC_000913.3), that contains entries as
  
  ```
   gene            190..255
                   /gene="thrL"
                   /locus_tag="b0001"
                   /gene_synonym="ECK0001; JW4367"
                   /db_xref="EcoGene:EG11277"
                   /db_xref="GeneID:944742"
   CDS             190..255
                   /gene="thrL"
                   /locus_tag="b0001"
                   /gene_synonym="ECK0001; JW4367"
                   /function="leader; Amino acid biosynthesis: Threonine"
                   /GO_process="GO:0009088 - threonine biosynthetic process"
                   /codon_start=1
                   /transl_table=11
                   /product="thr operon leader peptide"
                   /protein_id="NP_414542.1"
                   /db_xref="ASAP:ABE-0000006"
                   /db_xref="UniProtKB/Swiss-Prot:P0AD86"
                   /db_xref="EcoGene:EG11277"
                   /db_xref="GeneID:944742"
                   /translation="MKRISTTITTTITITTGNGAG"
  
  ```
  
  and I want to extract the potein fasta from it, how would I do this?
  
  I found a code sample [here](https://warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/genbank2fasta/). When I then run:
  
  ```
  from Bio import SeqIO
  
  gbk_filename = 'NC_000913.3.gb'
  faa_filename = 'NC_000913.3_warwick.fasta'
  input_handle  = open(gbk_filename, "r")
  output_handle = open(faa_filename, "w")
  
  for seq_record in SeqIO.parse(input_handle, "genbank") :
      print "Dealing with GenBank record %s" % seq_record.id
      for seq_feature in seq_record.features :
          if seq_feature.type=="CDS" :
              assert len(seq_feature.qualifiers['translation'])==1
              output_handle.write(">%s from %s\n%s\n" % (
                     seq_feature.qualifiers['locus_tag'][0],
                     seq_record.name,
                     seq_feature.qualifiers['translation'][0]))
  
  output_handle.close()
  input_handle.close()
  
  ```
  
  it results in
  
  ```
       31     for seq_feature in seq_record.features :
       32         if seq_feature.type=="CDS" :
  ---> 33             assert len(seq_feature.qualifiers['translation'])==1
       34             output_handle.write(">%s from %s\n%s\n" % (
       35                    seq_feature.qualifiers['locus_tag'][0],
  
  KeyError: 'translation'
  
  ```
  
  How could this be fixed?
  
  **Tags:** fasta, python, genbank
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_0 on 2018-05-25. Score: 6 | Accepted answer
  
  One can get it to work by using [`SeqIO.InsdcIO.GenBankCdsFeatureIterator`](http://biopython.org/DIST/docs/api/Bio.SeqIO.InsdcIO-module.html#GenBankCdsFeatureIterator):
  
  ```
  from Bio import SeqIO
  
  file_name = 'NC_000913.3.gb'
  
  # stores all the CDS entries
  all_entries = []
  
  with open(file_name, 'r') as GBFile:
  
      GBcds = SeqIO.InsdcIO.GenBankCdsFeatureIterator(GBFile)
  
      for cds in GBcds:
          if cds.seq is not None:
              cds.id = cds.name
              cds.description = ''
              all_entries.append(cds)
  
  # write file
  SeqIO.write(all_entries, '{}.fasta'.format(file_name[:-3]), 'fasta')
  
  ```
  
  This will then give the desired output (just the first two entries):
  
  ```
  >b0001
  MKRISTTITTTITITTGNGAG
  >b0002
  MRVLKFGGTSVANAERFLRVADILESNARQGQVATVLSAPAKITNHLVAMIEKTISGQDA
  LPNISDAERIFAELLTGLAAAQPGFPLAQLKTFVDQEFAQIKHVLHGISLLGQCPDSINA
  ALICRGEKMSIAIMAGVLEARGHNVTVIDPVEKLLAVGHYLESTVDIAESTRRIAASRIP
  ADHMVLMAGFTAGNEKGELVVLGRNGSDYSAAVLAACLRADCCEIWTDVDGVYTCDPRQV
  PDARLLKSMSYQEAMELSYFGAKVLHPRTITPIAQFQIPCLIKNTGNPQAPGTLIGASRD
  EDELPVKGISNLNNMAMFSVSGPGMKGMVGMAARVFAAMSRARISVVLITQSSSEYSISF
  CVPQSDCVRAERAMQEEFYLELKEGLLEPLAVTERLAIISVVGDGMRTLRGISAKFFAAL
  ARANINIVAIAQGSSERSISVVVNNDDATTGVRVTHQMLFNTDQVIEVFVIGVGGVGGAL
  LEQLKRQQSWLKNKHIDLRVCGVANSKALLTNVHGLNLENWQEELAQAKEPFNLGRLIRL
  VKEYHLLNPVIVDCTSSQAVADQYADFLREGFHVVTPNKKANTSSMDYYHQLRYAAEKSR
  RKFLYDTNVGAGLPVIENLQNLLNAGDELMKFSGILSGSLSYIFGKLDEGMSFSEATTLA
  REMGYTEPDPRDDLSGMDVARKLLILARETGRELELADIEIEPVLPAEFNAEGDVAAFMA
  NLSQLDDLFAARVAKARDEGKVLRYVGNIDEDGVCRVKIAEVDGNDPLFKVKNGENALAF
  YSHYYQPLPLVLRGYGAGNDVTAAGVFADLLRTLSWKLGV
  
  ```
  
  > **Comments:**
  > **username_1**: Is there any way to include the proteins names annotated at the gbk file as the sequence description?  
  
  ---
  
  