Error while writing fasta file using biopython

不问归期 提交于 2020-12-11 21:59:12

问题


I used the following code to write the fasta sequence into file.

from Bio import SeqIO
sequences = "KKPPLLRR" # add code here
output_handle = open("example.fasta", "w")
SeqIO.write(sequences, output_handle, "fasta")
output_handle.close()

I got the following error:

self = <Bio.SeqIO.FastaIO.FastaWriter object at 0x21c1d10>, record = 'M'
def write_record(self, record):
    """Write a single Fasta record to the file."""
    assert self._header_written
    assert not self._footer_written
    self._record_written = True

    if self.record2title:
        title = self.clean(self.record2title(record))
    else:
      id = self.clean(record.id)
    AttributeError: 'str' object has no attribute 'id'

Can somebody provide a solution for this error?


回答1:


That error tells you that sequences is not a set of SeqRecord objects. You cannot pass some string to the SeqIO.write. That's how it should be done:

from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC


sequences = []
record = SeqRecord(Seq("KKPPLLRR", IUPAC.protein), id="My_protein")
sequences.append(record)

Now you can pass sequences to the SeqIO.write. If you have a lot of sequences, you can create some generator that can be passed to SeqIO.write:

def generator_of_sequences():
    for string_seq in some_source_of_sequences:
        yield SeqRecord(Seq(string_seq, IUPAC.protein), id="Some_ID")

SeqIO.write(generator_of_sequences(), output_handle, "fasta")


来源:https://stackoverflow.com/questions/26646925/error-while-writing-fasta-file-using-biopython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!