code: def atomic_write(path, mode='wt', permissions=None, file_factory=None, **kwargs):
      
      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
docs: 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