[BioPython] String instead of file

Brad Chapman chapmanb@arches.uga.edu
Tue, 11 Sep 2001 08:20:49 -0400


Hi Yair;

> But, how do I parse strings and not a file with this parser?
> I am creating sequences and I want to write the in a Fasta format.
> Simply making a handle does not work, the error is:
> 
> ValueError: I expected a file handle of file-like object

Basically, you need to convert the string into a handle using 
the StringIO module. I wrote a little about handles in general (and
handles with strings specifically) in the biopython documentation:

http://www.bioinformatics.org/bradstuff/bp/tut/Tutorial006.html#toc29

Here's a concrete example of doing what you want to do in the
interpreter:

>>> fasta_string = "> First Fasta\nGATCGATC\n> Second Fasta\nAAAATTTT\n"
>>> print fasta_string
> First Fasta
GATCGATC
> Second Fasta
AAAATTTT

>>> import StringIO                 
>>> fasta_handle = StringIO.StringIO(fasta_string)
>>> from Bio import Fasta
>>> parser = Fasta.RecordParser()
>>> iterator = Fasta.Iterator(fasta_handle, parser)
>>> record = iterator.next()
>>> print record
> First Fasta
GATCGATC

Hopefully this helps -- let us know if this isn't clear!
Brad