def to_filehandle(fname, flag='<STR_LIT:r>', return_opened=False):
if is_string_like(fname):<EOL><INDENT>if fname.endswith('<STR_LIT>'):<EOL><INDENT>import gzip<EOL>fh = gzip.open(fname, flag)<EOL><DEDENT>else:<EOL><INDENT>fh = file(fname, flag)<EOL><DEDENT>opened = True<EOL><DEDENT>elif hasattr(fname, '<STR_LIT>'):<EOL><INDENT>fh = fname<EOL>opened = False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if return_opened:<EOL><INDENT>return fh, opened<EOL><DEDENT>return fh<EOL>
*fname* can be a filename or a file handle.  Support for gzipped
files is automatic, if the filename ends in .gz.  *flag* is a
read/write flag for :func:`file`