Back to index

python-biopython  1.60
Classes | Functions
Bio.File Namespace Reference

Classes

class  UndoHandle
class  StringHandle
class  SGMLStripper

Functions

def as_handle

Function Documentation

def Bio.File.as_handle (   handleish,
  mode = 'r',
  kwargs 
)
Context manager for arguments that can be passed to
SeqIO and AlignIO read, write, and parse methods: either file objects or strings.

When given a string, returns a file handle open to handleish with provided
mode which will be closed when the manager exits.

All other inputs are returned, and are *not* closed

- handleish  - Either a string or file handle
- mode       - Mode to open handleish (used only if handleish is a string)
- kwargs     - Further arguments to pass to open(...)

Example:

>>> with as_handle('seqs.fasta', 'w') as fp:
...     fp.write('>test\nACGT')
>>> fp.closed
True

>>> handle = open('seqs.fasta', 'w')
>>> with as_handle(handle) as fp:
...     fp.write('>test\nACGT')
>>> fp.closed
False
>>> fp.close()

Definition at line 27 of file File.py.

00027 
00028 def as_handle(handleish, mode='r', **kwargs):
00029     """
00030     Context manager for arguments that can be passed to
00031     SeqIO and AlignIO read, write, and parse methods: either file objects or strings.
00032 
00033     When given a string, returns a file handle open to handleish with provided
00034     mode which will be closed when the manager exits.
00035 
00036     All other inputs are returned, and are *not* closed
00037 
00038     - handleish  - Either a string or file handle
00039     - mode       - Mode to open handleish (used only if handleish is a string)
00040     - kwargs     - Further arguments to pass to open(...)
00041 
00042     Example:
00043 
00044     >>> with as_handle('seqs.fasta', 'w') as fp:
00045     ...     fp.write('>test\nACGT')
00046     >>> fp.closed
00047     True
00048 
00049     >>> handle = open('seqs.fasta', 'w')
00050     >>> with as_handle(handle) as fp:
00051     ...     fp.write('>test\nACGT')
00052     >>> fp.closed
00053     False
00054     >>> fp.close()
00055     """
00056     if isinstance(handleish, basestring):
00057         with open(handleish, mode, **kwargs) as fp:
00058             yield fp
00059     else:
00060         yield handleish
00061 

Here is the call graph for this function:

Here is the caller graph for this function: