delete files in dir that match pattern
6081
def _purge(dir, pattern, reason=''):
    
    for f in os.listdir(dir):
        if re.search(pattern, f):
            print "Purging file {0}. {1}".format(f, reason)
            os.remove(os.path.join(dir, f))
545454
def match(self, files):
        """"""
        if not files:
            return set()

        if (self.matched_inherit.all_files()
                or self.matched_and_subdir.all_files()
                or self.matched_no_subdir.all_files()):
            # Optimization: one of the matched patterns matches everything
            # So simply return it
            return set(files)

        unmatched = set(files)
        matched = set()
        for pattern_set in self._matching_pattern_sets():
            pattern_set.match_files(matched, unmatched)
            if not unmatched:
                # Optimization: If we have matched all files already
                # simply return at this point - nothing else to do
                break

        return matched
270861
def remove_part_images(filename):
    """"""
    dirname = '{0}_files'.format(os.path.splitext(filename)[0])
    if os.path.exists(dirname):
        shutil.rmtree(dirname)
1095772
def rm_files_in_dir(path):
    
    for f in os.listdir(path):
        try:
            os.remove(f)
        except PermissionError:
            os.chmod(f, 0o777)
            try:
                os.remove(f)
            except Exception:
                pass
    return
393037
def _clean_dir(root, keep, exclude_pat):
    '''
    
    '''
    root = os.path.normcase(root)
    real_keep = _find_keep_files(root, keep)
    removed = set()

    def _delete_not_kept(nfn):
        if nfn not in real_keep:
            # -- check if this is a part of exclude_pat(only). No need to
            # check include_pat
            if not salt.utils.stringutils.check_include_exclude(
                    os.path.relpath(nfn, root), None, exclude_pat):
                return
            removed.add(nfn)
            if not __opts__['test']:
                try:
                    os.remove(nfn)
                except OSError:
                    __salt__['file.remove'](nfn)

    for roots, dirs, files in salt.utils.path.os_walk(root):
        for name in itertools.chain(dirs, files):
            _delete_not_kept(os.path.join(roots, name))
    return list(removed)
1057283
def remove_directories(list_of_paths):
    
    found_dirs = set('/')
    for path in list_of_paths:
        dirs = path.strip().split('/')
        for i in range(2,len(dirs)):
            found_dirs.add( '/'.join(dirs[:i]) )

    paths = [ path for path in list_of_paths if
              (path.strip() not in found_dirs) and path.strip()[-1]!='/' ]
    return paths
748438
def file_matches_regexps(filename, patterns):
    """"""
    return any(re.match(pat, filename) for pat in patterns)
21421
private void deleteNonShuffleFiles(String[] dirs) {
    FilenameFilter filter = new FilenameFilter() {
      @Override
      public boolean accept(File dir, String name) {
        // Don't delete shuffle data or shuffle index files.
        return !name.endsWith(".index") && !name.endsWith(".data");
      }
    };

    for (String localDir : dirs) {
      try {
        JavaUtils.deleteRecursively(new File(localDir), filter);
        logger.debug("Successfully cleaned up non-shuffle files in directory: {}", localDir);
      } catch (Exception e) {
        logger.error("Failed to delete non-shuffle files in directory: " + localDir, e);
      }
    }
  }
722373
def match_filenames(filenames, pattern):
    """"""
    matching = []

    for filename in filenames:
        if fnmatch(get_filebase(filename, pattern), globify(pattern)):
            matching.append(filename)

    return matching
1118339
private void cleanDir(File dir) {
        File[] files = dir.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                // if file is a directory, first delete all the files inside, then delete the directory itself.
                if (file.isDirectory()) {
                    cleanDir(file);
                }
                if (!file.delete()) {
                    throw new BuildException(MessageFormat.format(messages.getString("error.cannot.delete.file"), file.getAbsolutePath()));
                }
            }
        }
    }
898639
def _glob(pattern, skip_dirs=False):
    """"""
    # Implicit recursive iff no / in pattern and starts with *
    if "/" not in pattern and pattern.startswith("*"):
        files = glob.glob(f"**/{pattern}", recursive=True)
    else:
        files = glob.glob(pattern, recursive=True)

    # Expand dirs
    all_files = set()
    for file in files:
        if os.path.isdir(file) and not skip_dirs:
            all_files.update(set(f for f in _glob(f"{file}/**/*", skip_dirs=True) if not os.path.isdir(f)))
        else:
            all_files.add(file)

    # Normalize all files
    return {str(Path(f)) for f in all_files}
906189
def find_files(path, filter="*.md"):
        
        if os.path.isfile(path):
            return [path]

        if os.path.isdir(path):
            matches = []
            for root, dirnames, filenames in os.walk(path):
                for filename in fnmatch.filter(filenames, filter):
                    matches.append(os.path.join(root, filename))
            return matches
1289093
def clean(cls, path):
        ''''''
        for pth in os.listdir(path):
            pth = os.path.abspath(os.path.join(path, pth))
            if os.path.isdir(pth):
                logger.debug('Removing directory %s' % pth)
                shutil.rmtree(pth)
            else:
                logger.debug('Removing file %s' % pth)
                os.remove(pth)
405767
def exclude_data_files(self, package, src_dir, files):
        """'"""
        files = list(files)
        patterns = self._get_platform_patterns(
            self.exclude_package_data,
            package,
            src_dir,
        )
        match_groups = (
            fnmatch.filter(files, pattern)
            for pattern in patterns
        )
        # flatten the groups of matches into an iterable of matches
        matches = itertools.chain.from_iterable(match_groups)
        bad = set(matches)
        keepers = (
            fn
            for fn in files
            if fn not in bad
        )
        # ditch dupes
        return list(_unique_everseen(keepers))
1228608
def remove_files(root_dir):
    
    for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
        for filename in filenames:
            os.remove(os.path.join(root_dir, filename))

        for dirname in dirnames:
            shutil.rmtree(os.path.join(root_dir, dirname))
462403
def exclude(self, pattern):
        """"""
        match = translate_pattern(pattern)
        return self._remove_files(match.match)
67642
static function unlinkWildcard( $dir, $pattern )
    {
        $availableFiles = array();
        if ( $handle = @opendir( $dir ) )
        {
            while ( ( $file = readdir( $handle ) ) !== false )
            {
                if ( $file != "." && $file != ".." )
                {
                    $availableFiles[] = $file;
                }
            }
            @closedir( $handle );

            if( strpos( $pattern, "." ) )
            {
                $baseexp = substr( $pattern, 0, strpos( $pattern, "." ) );
                $typeexp = substr( $pattern, ( strpos( $pattern, "." ) + 1 ), strlen( $pattern ) );
            }
            else
            {
                $baseexp = $pattern;
                $typeexp = "";
            }

            $baseexp=preg_quote( $baseexp );
            $typeexp=preg_quote( $typeexp );

            $baseexp = str_replace( array( "\*", "\?" ), array( ".*", "." ), $baseexp );
            $typeexp = str_replace(array( "\*", "\?" ), array( ".*", "." ), $typeexp );

            $i=0;
            $matchedFileArray = array();
            foreach( $availableFiles as $file )
            {
                $fileName = basename( $file );

                if( strpos( $fileName, "." ) )
                {
                    $base = substr( $fileName, 0, strpos( $fileName, "."));
                    $type = substr( $fileName, ( strpos( $fileName,"." ) + 1 ), strlen( $fileName ) );
                }
                else
                {
                    $base = $fileName;
                    $type = "";
                }

                if( preg_match( "/^".$baseexp."$/i", $base ) && preg_match( "/^".$typeexp."$/i", $type ) )
                {
                    $matchedFileArray[$i] = $file;
                    $i++;
                }
            }

            foreach ( array_keys( $matchedFileArray ) as $key )
            {
                $matchedFile =& $matchedFileArray[$key];
                if ( substr( $dir,-1 ) == "/")
                {
                    unlink( $dir.$matchedFile );
                }
                else
                {
                    unlink( $dir."/".$matchedFile );
                }
            }
        }
    }