Answers.Body: <p>Given the criteria required the closest solution is:</p>
  <pre><code>from Bio import SeqIO
  
  seq_obj = ... # Biopython seq_obj
  with open(&quot;mysequence.gb&quot;, &quot;w&quot;) as fout:
      SeqIO.write(seq_obj, fout, &quot;gb&quot;)
  </code></pre>
  <p>If this fails I would substitute <code>gb</code> for <code>fasta</code> and try again. If that fails, i.e. no fasta, there's a problem with the sequence object. If this succeeds but the <code>gb</code> fails, just supply a reproducible example. It will work.</p>
  <p>I've used <code>gb</code> to successfully write APIs against NCBI Genbank and trap the meta-data. Genbank format is really cool.</p>
  <p>Oh wait, sorry the answer is  ...</p>
  <pre><code>seq_obj for records:
      print(seq_obj.format(&quot;gb&quot;))
  </code></pre>
  <hr />
  <p>From the comments &quot;molecule type&quot;...</p>
  <p>Which are you using</p>
  <pre><code>for record in SeqIO.parse(filename, &quot;fasta&quot;):
  </code></pre>
  <p>or</p>
  <pre><code>for record in SeqIO.read(filename, &quot;fasta&quot;):
  </code></pre>
  <p>Which ever is used I'd to the other method.</p>
  <p>Just to comment on @RamRS solution, thats cool I didn't know.</p>
  <pre><code>for record in SeqIO.parse(filename, &quot;fasta&quot;):
      record.annotations = {&quot;molecule_type&quot; : &quot;protein&quot; }
  </code></pre>
  <p>What is happening is the instance is being manually set. However, Biopython should detected the data type automatically. My suspicion is that <code>read</code> or <code>parse</code> one comprises and automated data type setter.</p>
  <p>In any case, RamRS's solution is useful and will work. In past coding I would have read the object via Genbank.</p>
  <p>The old <code>alphabet</code> method is deprecated and shouldn't be attempted.</p>
  <hr />
  <p>For future reference RamRS's code is described <a href="https://github.com/biopython/biopython/issues/3156" rel="nofollow noreferrer">here</a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T18:36:58.000Z
Answers.Text: I fixed it using this: `with open("xyz.fa") as handle: for record in SeqIO.parse(handle, "fasta"): record.annotations = {"molecule_type" : "protein" } SeqIO.write(record, "xyz.gb", "gb")` (excuse the bad python)
Answers.UserDisplayName: Ram RS
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T18:37:39.700Z
Answers.Text: Code from: https://github.com/biopython/biopython/issues/3156
Answers.UserDisplayName: Ram RS
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T21:11:31.787Z
Answers.Text: @RamRS Maybe possibly give Leptoceratops an upvote? This question has been a long haul for everyone, but it's a good answer.
Answers.UserDisplayName: M__
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T21:18:58.023Z
Answers.Text: Sure thing, they have been very cooperative and clear. I appreciate their contribution
Answers.UserDisplayName: Ram RS
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T18:25:30.947Z
Answers.LastActivityDate: 2023-06-06T21:54:46.320Z
Answers.LastEditDate: 2023-06-06T21:54:46.320Z
Answers.UserDisplayName: M__
Answers.Body: <p>@M__ is right - there's a <code>molecule_type</code> error when you try to write and this needs to be fixed. Here's my end to end approach:</p>
  <p>The input file:</p>
  <pre><code>cat xyz.fa
  &gt;NP_000537.3 cellular tumor antigen p53 isoform a [Homo sapiens]
  MEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGPDEAPRMPEAA
  PPVAPAPAAPTPAAPAPAPSWPLSSSVPSQKTYQGSYGFRLGFLHSGTAKSVTCTYSPALNKMFCQLAKT
  CPVQLWVDSTPPPGTRVRAMAIYKQSQHMTEVVRRCPHHERCSDSDGLAPPQHLIRVEGNLRVEYLDDRN
  TFRHSVVVPYEPPEVGSDCTTIHYNYMCNSSCMGGMNRRPILTIITLEDSSGNLLGRNSFEVRVCACPGR
  DRRTEEENLRKKGEPHHELPPGSTKRALPNNTSSSPQPKKKPLDGEYFTLQIRGRERFEMFRELNEALEL
  KDAQAGKEPGGSRAHSSHLKSKKGQSTSRHKKLMFKTEGPDSD
  </code></pre>
  <p>My (bad) code:</p>
  <pre class="lang-py prettyprint-override"><code>from Bio import SeqIO
  
  with open(&quot;xyz.fa&quot;) as handle:
      for record in SeqIO.parse(handle, &quot;fasta&quot;):
          record.annotations = { &quot;molecule_type&quot; : &quot;protein&quot; }
  SeqIO.write(record, &quot;xyz.gb&quot;, &quot;gb&quot;) # moved two indentations to the left
  </code></pre>
  <p>The output:</p>
  <pre><code>cat xyz.gb
  
  LOCUS       NP_000537.3              393 aa                     UNK 01-JAN-1980
  DEFINITION  NP_000537.3 cellular tumor antigen p53 isoform a [Homo sapiens].
  ACCESSION   NP_000537
  VERSION     NP_000537.3
  KEYWORDS    .
  SOURCE      .
    ORGANISM  .
              .
  FEATURES             Location/Qualifiers
  ORIGIN
          1 meepqsdpsv epplsqetfs dlwkllpenn vlsplpsqam ddlmlspddi eqwftedpgp
         61 deaprmpeaa ppvapapaap tpaapapaps wplsssvpsq ktyqgsygfr lgflhsgtak
        121 svtctyspal nkmfcqlakt cpvqlwvdst pppgtrvram aiykqsqhmt evvrrcphhe
        181 rcsdsdglap pqhlirvegn lrveylddrn tfrhsvvvpy eppevgsdct tihynymcns
        241 scmggmnrrp iltiitleds sgnllgrnsf evrvcacpgr drrteeenlr kkgephhelp
        301 pgstkralpn ntssspqpkk kpldgeyftl qirgrerfem frelnealel kdaqagkepg
        361 gsrahsshlk skkgqstsrh kklmfktegp dsd
  //
  </code></pre>
  <p>I used the code from <a href="https://github.com/biopython/biopython/issues/3156" rel="nofollow noreferrer">https://github.com/biopython/biopython/issues/3156</a> to fix the <code>ValueError: missing molecule_type in annotations</code> that I faced when I'd skipped the <code>record.annotations = {&quot;molecule_type&quot; : &quot;protein&quot; }</code> line.</p>
  <p>There is definitely a better way to write the python code instead of using a loop or at least writing to a static file from within a loop, but that's not central to the problem here so I'm choosing to ignore it. I welcome any improvements to the code.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T19:52:37.680Z
Answers.Text: I've moved this two indentations to the left (one indentation left is okay). The example will work because it's just one sequence. Any more sequences will trigger overwriting.
Answers.UserDisplayName: M__
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T19:42:11.633Z
Answers.LastActivityDate: 2023-06-06T19:50:53.963Z
Answers.LastEditDate: 2023-06-06T19:50:53.963Z
Answers.UserDisplayName: Ram RS
Body: <p>Is there an out-of-the-box function in the <code>Bio.SeqIO</code> module (in <code>biopython</code>) that can print a protein sequence (in command line) in multiple lines along with the numbering of the residues (either left and right or in-between the lines)?</p>
  <p>In particular I have a <code>.fasta</code> file which I can read into a <code>SeqRecord</code> object like so:</p>
  <pre><code>from Bio import SeqIO
  record = SeqIO.read(&quot;protein.fasta&quot;, &quot;fasta&quot;)
  </code></pre>
  <p>I would like to then print the <code>Seq</code> class with the numbering, not just as a string as shown below:</p>
  <pre><code>print(record.seq)
  </code></pre>
  <p>I have already tried:</p>
  <pre><code>SeqIO.write(record, sys.stdout, 'gb')
  </code></pre>
  <p>But it is not working for me. The error was <code>ValueError: missing molecule_type in annotations</code>. I googled it and it appears to be related to newer biopython versions (see <a href="https://github.com/linsalrob/PhiSpy/issues/43" rel="nofollow noreferrer">https://github.com/linsalrob/PhiSpy/issues/43</a>).</p>
  <p><a href="http://sequenceconversion.bugaco.com/converter/biology/sequences/fasta_to_genbank.php" rel="nofollow noreferrer">This on-line tool</a> seems to do what I want, but one needs to provide it with an alphabet. How do I do that with code? Does a <code>SeqRecord</code> object have an alphabet?</p>
  
Tags: <sequence><biopython><command-line>
Title: Residue numbering in biopython
ThreadText: # Residue numbering in biopython
  
  (Asked by: username_0 on 2023-06-06)
  
  Is there an out-of-the-box function in the `Bio.SeqIO` module (in `biopython`) that can print a protein sequence (in command line) in multiple lines along with the numbering of the residues (either left and right or in-between the lines)?
  
  In particular I have a `.fasta` file which I can read into a `SeqRecord` object like so:
  
  ```
  from Bio import SeqIO
  record = SeqIO.read("protein.fasta", "fasta")
  
  ```
  
  I would like to then print the `Seq` class with the numbering, not just as a string as shown below:
  
  ```
  print(record.seq)
  
  ```
  
  I have already tried:
  
  ```
  SeqIO.write(record, sys.stdout, 'gb')
  
  ```
  
  But it is not working for me. The error was `ValueError: missing molecule_type in annotations`. I googled it and it appears to be related to newer biopython versions (see <https://github.com/linsalrob/PhiSpy/issues/43>).
  
  [This on-line tool](http://sequenceconversion.bugaco.com/converter/biology/sequences/fasta_to_genbank.php) seems to do what I want, but one needs to provide it with an alphabet. How do I do that with code? Does a `SeqRecord` object have an alphabet?
  
  **Tags:** sequence, biopython, command-line
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_2 on 2023-06-06. Score: 3 | Accepted answer
  
  @M\_\_ is right - there's a `molecule_type` error when you try to write and this needs to be fixed. Here's my end to end approach:
  
  The input file:
  
  ```
  cat xyz.fa
  >NP_000537.3 cellular tumor antigen p53 isoform a [Homo sapiens]
  MEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGPDEAPRMPEAA
  PPVAPAPAAPTPAAPAPAPSWPLSSSVPSQKTYQGSYGFRLGFLHSGTAKSVTCTYSPALNKMFCQLAKT
  CPVQLWVDSTPPPGTRVRAMAIYKQSQHMTEVVRRCPHHERCSDSDGLAPPQHLIRVEGNLRVEYLDDRN
  TFRHSVVVPYEPPEVGSDCTTIHYNYMCNSSCMGGMNRRPILTIITLEDSSGNLLGRNSFEVRVCACPGR
  DRRTEEENLRKKGEPHHELPPGSTKRALPNNTSSSPQPKKKPLDGEYFTLQIRGRERFEMFRELNEALEL
  KDAQAGKEPGGSRAHSSHLKSKKGQSTSRHKKLMFKTEGPDSD
  
  ```
  
  My (bad) code:
  
  ```py
  from Bio import SeqIO
  
  with open("xyz.fa") as handle:
      for record in SeqIO.parse(handle, "fasta"):
          record.annotations = { "molecule_type" : "protein" }
  SeqIO.write(record, "xyz.gb", "gb") # moved two indentations to the left
  
  ```
  
  The output:
  
  ```
  cat xyz.gb
  
  LOCUS       NP_000537.3              393 aa                     UNK 01-JAN-1980
  DEFINITION  NP_000537.3 cellular tumor antigen p53 isoform a [Homo sapiens].
  ACCESSION   NP_000537
  VERSION     NP_000537.3
  KEYWORDS    .
  SOURCE      .
    ORGANISM  .
              .
  FEATURES             Location/Qualifiers
  ORIGIN
          1 meepqsdpsv epplsqetfs dlwkllpenn vlsplpsqam ddlmlspddi eqwftedpgp
         61 deaprmpeaa ppvapapaap tpaapapaps wplsssvpsq ktyqgsygfr lgflhsgtak
        121 svtctyspal nkmfcqlakt cpvqlwvdst pppgtrvram aiykqsqhmt evvrrcphhe
        181 rcsdsdglap pqhlirvegn lrveylddrn tfrhsvvvpy eppevgsdct tihynymcns
        241 scmggmnrrp iltiitleds sgnllgrnsf evrvcacpgr drrteeenlr kkgephhelp
        301 pgstkralpn ntssspqpkk kpldgeyftl qirgrerfem frelnealel kdaqagkepg
        361 gsrahsshlk skkgqstsrh kklmfktegp dsd
  //
  
  ```
  
  I used the code from <https://github.com/biopython/biopython/issues/3156> to fix the `ValueError: missing molecule_type in annotations` that I faced when I'd skipped the `record.annotations = {"molecule_type" : "protein" }` line.
  
  There is definitely a better way to write the python code instead of using a loop or at least writing to a static file from within a loop, but that's not central to the problem here so I'm choosing to ignore it. I welcome any improvements to the code.
  
  > **Comments:**
  > **username_1**: I've moved this two indentations to the left (one indentation left is okay). The example will work because it's just one sequence. Any more sequences will trigger overwriting.  
  
  ---
  
  ### Answer by username_1 on 2023-06-06. Score: 0
  
  Given the criteria required the closest solution is:
  
  ```
  from Bio import SeqIO
  
  seq_obj = ... # Biopython seq_obj
  with open("mysequence.gb", "w") as fout:
      SeqIO.write(seq_obj, fout, "gb")
  
  ```
  
  If this fails I would substitute `gb` for `fasta` and try again. If that fails, i.e. no fasta, there's a problem with the sequence object. If this succeeds but the `gb` fails, just supply a reproducible example. It will work.
  
  I've used `gb` to successfully write APIs against NCBI Genbank and trap the meta-data. Genbank format is really cool.
  
  Oh wait, sorry the answer is ...
  
  ```
  seq_obj for records:
      print(seq_obj.format("gb"))
  
  ```
  
  ---
  
  From the comments "molecule type"...
  
  Which are you using
  
  ```
  for record in SeqIO.parse(filename, "fasta"):
  
  ```
  
  or
  
  ```
  for record in SeqIO.read(filename, "fasta"):
  
  ```
  
  Which ever is used I'd to the other method.
  
  Just to comment on @username_2 solution, thats cool I didn't know.
  
  ```
  for record in SeqIO.parse(filename, "fasta"):
      record.annotations = {"molecule_type" : "protein" }
  
  ```
  
  What is happening is the instance is being manually set. However, Biopython should detected the data type automatically. My suspicion is that `read` or `parse` one comprises and automated data type setter.
  
  In any case, username_2's solution is useful and will work. In past coding I would have read the object via Genbank.
  
  The old `alphabet` method is deprecated and shouldn't be attempted.
  
  ---
  
  For future reference username_2's code is described [here](https://github.com/biopython/biopython/issues/3156)
  
  > **Comments:**
  > **username_2**: I fixed it using this: `with open("xyz.fa") as handle: for record in SeqIO.parse(handle, "fasta"): record.annotations = {"molecule_type" : "protein" } SeqIO.write(record, "xyz.gb", "gb")` (excuse the bad python)  
  > **username_2**: Code from: https://github.com/biopython/biopython/issues/3156  
  > **username_1**: @username_2 Maybe possibly give username_0 an upvote? This question has been a long haul for everyone, but it's a good answer.  
  > **username_2**: Sure thing, they have been very cooperative and clear. I appreciate their contribution  
  
  ---
  
  