<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def atomic_write(path, mode='wt', permissions=None, file_factory=None, **kwargs):
 """ Open a file for atomic writing. Generates a temp file, renames to value of ``path``. Arguments: ``permissions``: Permissions to set (default: umask) ``file_factory``: If given, the handle yielded will be the result of calling file_factory(path) Additional arguments are passed to tempfile.NamedTemporaryFile """

    if permissions is None:
        permissions = apply_umask()
    # Handle stdout:
    if path == '-':
        yield sys.stdout
    else:
        base_dir = os.path.dirname(path)
        kwargs['suffix'] = os.path.basename(path)
        tf = tempfile.NamedTemporaryFile(
            dir=base_dir, mode=mode, delete=False, **kwargs)

        # If a file_factory is given, close, and re-open a handle using the
        # file_factory
        if file_factory is not None:
            tf.close()
            tf = file_factory(tf.name)
        try:
            with tf:
                yield tf
            # Move
            os.rename(tf.name, path)
            os.chmod(path, permissions)
        except:
            os.remove(tf.name)
            raise