@contextlib.contextmanager<EOL>def create_file(fname=None, fname_tmp=None, tmpdir=None,<EOL>save_tmpfile=False, keepext=False):
<EOL>if fname == '<STR_LIT>':<EOL><INDENT>yield fname<EOL>return<EOL><DEDENT>if fname_tmp is None:<EOL><INDENT>basename = os.path.basename(fname)<EOL>root, ext = os.path.splitext(basename)<EOL>dir_ = this_dir = os.path.dirname(fname)<EOL>if not keepext:<EOL><INDENT>root = root + ext<EOL>ext = '<STR_LIT>'<EOL><DEDENT>if tmpdir:<EOL><INDENT>if tmpdir is True:<EOL><INDENT>for dir__ in possible_tmpdirs:<EOL><INDENT>if os.access(dir__, os.F_OK):<EOL><INDENT>dir_ = dir__<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>tmpfile = tempfile.NamedTemporaryFile(<EOL>prefix='<STR_LIT>' + root + '<STR_LIT:->', suffix=ext, dir=dir_, delete=False)<EOL>fname_tmp = tmpfile.name<EOL><DEDENT>try:<EOL><INDENT>yield fname_tmp<EOL><DEDENT>except Exception as e:<EOL><INDENT>if save_tmpfile:<EOL><INDENT>print("<STR_LIT>" % fname_tmp)<EOL><DEDENT>else:<EOL><INDENT>os.unlink(fname_tmp)<EOL><DEDENT>raise<EOL><DEDENT>try:<EOL><INDENT>os.rename(fname_tmp, fname)<EOL>os.chmod(fname, <NUM_LIT> & ~current_umask)<EOL><DEDENT>except OSError as e:<EOL><INDENT>tmpfile2 = tempfile.NamedTemporaryFile(<EOL>prefix='<STR_LIT>' + root + '<STR_LIT:->', suffix=ext, dir=this_dir, delete=False)<EOL>shutil.copy(fname_tmp, tmpfile2.name)<EOL>os.rename(tmpfile2.name, fname)<EOL>os.chmod(fname, <NUM_LIT> & ~current_umask)<EOL>os.unlink(fname_tmp)<EOL><DEDENT>
Context manager for making files with possibility of failure.

    If you are creating a file, it is possible that the code will fail
    and leave a corrupt intermediate file.  This is especially damaging
    if this is used as automatic input to another process.  This context
    manager helps by creating a temporary filename, your code runs and
    creates that temporary file, and then if no exceptions are raised,
    the context manager will move the temporary file to the original
    filename you intended to open.

    Parameters
    ----------
    fname : str
        Target filename, this file will be created if all goes well
    fname_tmp : str
        If given, this is used as the temporary filename.
    tmpdir : str or bool
        If given, put temporary files in this directory.  If `True`,
        then find a good tmpdir that is not on local filesystem.
    save_tmpfile : bool
        If true, the temporary file is not deleteted if an exception
        is raised.
    keepext : bool, default False
            If true, have tmpfile have same extension as final file.

    Returns (as context manager value)
    ----------------------------------
     fname_tmp: str
        Temporary filename to be used.  Same as `fname_tmp`
        if given as an argument.

    Raises
    ------
    Re-raises any except occuring during the context block.