Recursively delete a directory tree on a remote server.

        Source: https://gist.github.com/artlogic/2632647
346455
def _rm_recursive(self, ftp, path):
        
        wd = ftp.pwd()

        # check if it is a file first, because some FTP servers don't return
        # correctly on ftp.nlst(file)
        try:
            ftp.cwd(path)
        except ftplib.all_errors:
            # this is a file, we will just delete the file
            ftp.delete(path)
            return

        try:
            names = ftp.nlst()
        except ftplib.all_errors:
            # some FTP servers complain when you try and list non-existent paths
            return

        for name in names:
            if os.path.split(name)[1] in ('.', '..'):
                continue

            try:
                ftp.cwd(name)   # if we can cwd to it, it's a folder
                ftp.cwd(wd)   # don't try a nuke a folder we're in
                ftp.cwd(path)  # then go back to where we were
                self._rm_recursive(ftp, name)
            except ftplib.all_errors:
                ftp.delete(name)

        try:
            ftp.cwd(wd)  # do not delete the folder that we are in
            ftp.rmd(path)
        except ftplib.all_errors as e:
            print('_rm_recursive: Could not remove {0}: {1}'.format(path, e))
164318
def clean_dir(root):
    ''''''
    for x in root.walkdirs('.*', errors='ignore'):
        x.rmtree()
    for x in root.walkdirs('_*', errors='ignore'):
        x.rmtree()

    for x in root.walkfiles('.*', errors='ignore'):
        x.remove()
    for x in root.walkfiles('_*', errors='ignore'):
        x.remove()
365599
function clean(directoryPath, isRoot, done) {
  fs.stat(directoryPath, function(err, stat) {
    if (err) return done(isRoot ? undefined : err);
    if (stat.isFile()) return fs.unlink(directoryPath, done);
    fs.readdir(directoryPath, function(err, relativePaths) {
      if (err) return done(err);
      each(relativePaths, function(relativePath, next) {
        var absolutePath = path.join(directoryPath, relativePath);
        fs.stat(absolutePath, function(err, stats) {
          if (err) return next(err);
          if (!stats.isDirectory()) return fs.unlink(absolutePath, next);
          clean(absolutePath, false, next);
        });
      }, function(err) {
        if (err) return done(err);
        fs.rmdir(directoryPath, done);
      });
    });
  });
}
1294477
def delete(path, dryrun=False, recursive=True, verbose=None, print_exists=True,
           ignore_errors=True):
    
    if verbose is None:
        verbose = VERBOSE
        if not QUIET:
            verbose = 1
    if verbose > 0:
        print('[util_path] Deleting path=%r' % path)
    exists_flag = exists(path)
    link_flag = islink(path)
    if not exists_flag and not link_flag:
        if print_exists and verbose:
            print('..does not exist!')
        flag = False
    else:
        rmargs = dict(verbose=verbose > 1, ignore_errors=ignore_errors,
                      dryrun=dryrun)
        if islink(path):
            os.unlink(path)
            flag = True
        elif isdir(path):
            # First remove everything in the directory
            flag = remove_files_in_dir(path, recursive=recursive, **rmargs)
            # Then remove the directory itself
            flag = flag and remove_dirs(path, **rmargs)
        elif isfile(path):
            flag = remove_file(path, **rmargs)
        else:
            raise ValueError('Unknown type of path=%r' % (path,))
        if verbose > 0:
            print('[util_path] Finished deleting path=%r' % path)
    return flag
982390
public static void deleteSilentlyRecursively(final Path path) {
        if (path != null) {
            try {
                deleteRecursively(path);
            } catch (IOException ioex) {
                DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(ioex, path);
            }
        }
    }
138221
def remote_delete(self, remote_path, r_st):
        """"""
        # If it's a directory, then delete content and directory
        if S_ISDIR(r_st.st_mode):
            for item in self.sftp.listdir_attr(remote_path):
                full_path = path_join(remote_path, item.filename)
                self.remote_delete(full_path, item)
            self.sftp.rmdir(remote_path)

        # Or simply delete files
        else:
            try:
                self.sftp.remove(remote_path)
            except FileNotFoundError as e:
                self.logger.error(
                    "error while removing {}. trace: {}".format(remote_path, e)
                )
968789
public static void deleteIfExists(FileSystem fs, Path path, boolean recursive) throws IOException {
    if (fs.exists(path)) {
      deletePath(fs, path, recursive);
    }
  }
29983
def __remove_dir(self, ftp, remote_path):
        
        # Iterate over the remote path and perform remove operations
        files = ftp.listdir(remote_path)
        for filename in files:
            # Attempt to remove the file (if exception then path is directory)
            path = remote_path + self.separator + filename
            try:
                ftp.remove(path)
            except IOError:
                self.__remove_dir(ftp, path)

        # Remove the original directory requested
        ftp.rmdir(remote_path)
166517
def rm_rf(path, dry_run=False):
    
    log.info("removing %s" % path)
    if dry_run:
        return
    try:
        if os.path.isdir(path) and not os.path.islink(path):
            shutil.rmtree(path)
        else:
            os.remove(path)
    except OSError:
        pass
1132589
static public void delete(Configuration conf, Path src, FileSystem srcFs, boolean recursive,
                      boolean skipTrash, boolean ignoreNonEmpty,
                      boolean onlyDeleteFile) throws IOException {
    FileStatus fs = null;
    try {
      fs = srcFs.getFileStatus(src);
    } catch (FileNotFoundException fnfe) {
      // Have to re-throw so that console output is as expected
      throw new FileNotFoundException("cannot remove "
          + src + ": No such file or directory.");
    }

    if (fs.isDir() && !recursive) {
      // We may safely delete empty directories if
      // the recursive option is not specified
      FileStatus children[] = srcFs.listStatus(src);
      if (onlyDeleteFile || (children != null && children.length != 0)) {
        if (ignoreNonEmpty) {
          return;
        } else {
          throw new IOException("Cannot remove directory \"" + src + "\"," +
              " use -rmr instead");
        }
      } else if (children == null) {
        throw new IOException(src + " no longer exists");
      }
    }

    if(!skipTrash) {
      try {
        Trash trashTmp = new Trash(srcFs, conf);
        if (trashTmp.moveToTrash(src)) {
          System.err.println("Moved to trash: " + src);
          return;
        }
      } catch (IOException e) {
        Exception cause = (Exception) e.getCause();
        String msg = "";
        if(cause != null) {
          msg = cause.getLocalizedMessage();
        }
        System.err.println("Problem with Trash." + msg +". Consider using -skipTrash option");
        throw e;
      }
    }

    if (srcFs.delete(src, recursive, true)) {
      System.err.println("Deleted " + src);
    } else {
      throw new IOException("Delete failed " + src);
    }
  }
145839
public static void recursivelyDeleteDirectory(File directory) throws IOException {
    if (!directory.exists()) {
      return;
    }
    checkArgument(directory.isDirectory(), "Cannot recursively delete a non-directory");
    walkFileTree(directory.toPath(), new DeletionFileVisitor());
  }
1341037
def delete(self):
        
        if self.exists:
            logger.info("Deleting %s" % self.path)
            shutil.rmtree(self.path)
804840
private boolean delete(String path, boolean recursive) throws IOException {
    IOException te = null;
    FileSystem hdfs = getFs();
    RetryPolicy retryPolicy = new CountingRetry(MAX_TRY);
    while (retryPolicy.attempt()) {
      try {
        return hdfs.delete(new Path(path), recursive);
      } catch (IOException e) {
        LOG.warn("Attempt count {} : {}", retryPolicy.getAttemptCount(), e.getMessage());
        te = e;
      }
    }
    throw te;
  }
537113
public static boolean deletePathRecursive(Tree<ResourceMeta> tree, Path path){
        if(tree.hasResource(path)) {
            //delete just this resource
            return tree.deleteResource(path);
        }else if (tree.hasDirectory(path)) {
            //list resources and delete
            Set<Resource<ResourceMeta>> resources = tree.listDirectory(path);
            boolean failed=false;
            for (Resource<ResourceMeta> resource : resources) {
                if(resource.isDirectory()){
                    if(!deletePathRecursive(tree,resource.getPath())){
                        failed=true;
                    }
                }else {
                    if(!tree.deleteResource(resource.getPath())){
                        failed=true;
                    }
                }
            }
            return !failed;
        }else{
            return true;
        }
    }
1074850
def delete(self, ignore=None):
        """"""
        ignore = ignore or []

        def _delete(tree_or_filename, alias=None):
            """Delete indexes and aliases by walking DFS."""
            if alias:
                yield alias, self.client.indices.delete_alias(
                    index=list(_get_indices(tree_or_filename)),
                    name=alias,
                    ignore=ignore,
                )

            # Iterate over aliases:
            for name, value in tree_or_filename.items():
                if isinstance(value, dict):
                    for result in _delete(value, alias=name):
                        yield result
                else:
                    yield name, self.client.indices.delete(
                        index=name,
                        ignore=ignore,
                    )

        for result in _delete(self.active_aliases):
            yield result
276400
def remove(self, path, recursive=True):
        
        if recursive:
            cmd = ["rm", "-r", path]
        else:
            cmd = ["rm", path]

        self.remote_context.check_output(cmd)
1239487
public function delete($remote_path, $recursive = false)
    {
        $remote_path = $this->_getAbsoluteRemotePath($remote_path);
        if (true === @is_dir($remote_path)) {
            if (true === $recursive) {
                foreach ($this->ls($remote_path) as $file) {
                    if ('.' !== $file && '..' !== $file) {
                        $this->delete($remote_path.DIRECTORY_SEPARATOR.$file, $recursive);
                    }
                }
            }

            if (false === @rmdir($remote_path)) {
                return $this->_trigger_error(sprintf('Unable to delete directory %s', $remote_path));
            }
        } else {
            if (false === @unlink($remote_path)) {
                return $this->_trigger_error(sprintf('Unable to delete file %s', $remote_path));
            }
        }

        return true;
    }