Loops through a parent directory and nests files within folders that already exists and have matching prefixs
    :param directory: Starting directory
775402
def move_files_to_folders(directory):
    
    # Generate lists of files and folders in root directory
    files, folders, files_to_move = [], [], []
    for path in os.listdir(directory):
        if os.path.isdir(path):
            folders.append(path)
        elif os.path.isfile(path):
            files.append(path)

    # Loop through folders in root directory
    for path in folders:
        # Generate list of files with same prefix as current folder
        child_files = [f for f in files if f.startswith(path)]
        files_to_move.append((path, child_files))

    # Move child files into parent folder
    for each in files_to_move:
        folder, files = each
        for f in files:
            shutil.move(f, folder)
268668
def chdir(directory):
    
    try:
        olddir = os.getcwd()
    except OSError:
        olddir = None
    os.chdir(directory)
    return olddir
128330
def chdir(directory):
    
    directory = os.path.abspath(directory)
    logger.info("chdir -> %s" % directory)
    try:
        if not os.path.isdir(directory):
            logger.error(
                "chdir -> %s failed! Directory does not exist!", directory
            )
            return False
        os.chdir(directory)
        return True
    except Exception as e:
        logger.error("chdir -> %s failed! %s" % (directory, e))
        return False
702469
def _os_walk(directory, recurse=True, **kwargs):
    
    if recurse:
        for root, dirs, files in os.walk(directory, **kwargs):
            yield root, dirs, files
    else:
        files = []
        for filename in os.listdir(directory):
            if os.path.isfile(os.path.join(directory, filename)):
                files.append(filename)
        yield directory, [], files
318758
private void addFilesFromDir(File dir) {
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
      if (!files[i].isDirectory()) {
        mFiles.add(files[i]);
      } else if (mRecursive) {
        addFilesFromDir(files[i]);
      }
    }
  }
233998
def load_directory(self, directory, **kwargs):
        
        log.setLevel(kwargs.get("log_level", self.log_level))
        conn = self.__get_conn__(**kwargs)
        file_extensions = kwargs.get('file_extensions', conn.rdf_formats)
        file_list = list_files(directory,
                               file_extensions,
                               kwargs.get('include_subfolders', False),
                               include_root=True)
        for file in file_list:
            self.load_file(file[1], **kwargs)
        log.setLevel(self.log_level)
631417
def find_files(directory, pattern):
    
    for root, __, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename
876140
public static void mkdirs(File directory) throws CreateDirectoryException {
    if (directory.exists()) {
      // file exists and *is* a directory
      if (directory.isDirectory()) {
        return;
      }

      // file exists, but is not a directory - delete it
      if (!directory.delete()) {
        throw new CreateDirectoryException(
            directory.getAbsolutePath(),
            new FileDeleteException(directory.getAbsolutePath()));
      }
    }

    // doesn't exist. Create one
    if (!directory.mkdirs() && !directory.isDirectory()) {
      throw new CreateDirectoryException(directory.getAbsolutePath());
    }
  }
902621
def cd(new_directory, clean_up=lambda: True):  # pylint: disable=invalid-name
    
    previous_directory = os.getcwd()
    os.chdir(os.path.expanduser(new_directory))
    try:
        yield
    finally:
        os.chdir(previous_directory)
        clean_up()
515303
def makedirs(self):
        
        normpath = os.path.normpath(self.path)
        parentfolder = os.path.dirname(normpath)
        if parentfolder:
            try:
                os.makedirs(parentfolder)
            except OSError:
                pass
1132409
def push(self, dir):
        
        self.stack.append(os.getcwd())
        os.chdir(dir or os.getcwd())
412279
def walk_links(directory, prefix='', linkbase=None):
    
    links = {}
    try:
        for child in os.listdir(directory):
            fullname = os.path.join(directory, child)
            if os.path.islink(fullname):
                link_path = os.path.normpath(os.path.join(directory, os.readlink(fullname)))
                if linkbase:
                    link_path = os.path.relpath(link_path, linkbase)
                links[os.path.join(prefix, child)] = link_path
            elif os.path.isdir(fullname):
                links.update(walk_links(fullname,
                                        prefix=os.path.join(prefix, child),
                                        linkbase=linkbase))
    except OSError as err:
        if err.errno != 2:  # Ignore unknown directory error
            raise
    return links
1301410
private List<String> listFiles( final File dir, final String parentName )
    {
        final List<String> fileNames = new ArrayList<String>();
        File[] files = null;
        if( dir.canRead() )
        {
            files = dir.listFiles();
        }
        if( files != null )
        {
            for( File file : files )
            {
                if( file.isDirectory() )
                {
                    fileNames.addAll( listFiles( file, parentName + file.getName() + "/" ) );
                }
                else
                {
                    fileNames.add( parentName + file.getName() );
                }
            }
        }
        return fileNames;
    }
1075168
def _walk_directory(root_directory):
        

        paths = [os.path.join(root, name)
                 for root, dirs, files in os.walk(root_directory)  # noqa
                 for name in files]
        paths.sort()
        return paths
1246306
def examples(directory):
    
    source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples")

    try:
        shutil.copytree(source_dir, os.path.join(directory, "examples"))
    except OSError as e:
        if e.errno == errno.EEXIST:
            six.print_("Folder examples is exists.")
1215922
def fetch_parent_dir(filepath, n=1):
    '''
    '''
    filepath = os.path.realpath(filepath)
    for i in range(n):
        filepath = os.path.dirname(filepath)
    return os.path.basename(filepath)
928539
function prepareDirectory($directory) {
    // Because we may have an absolute path whose base folders are not writable
    // we can't use the standard recursive D6 pattern.
    $pieces = explode('/', $directory);

    // Work up through the folder's parentage until we find a directory that exists.
    // (Or in other words, backwards in the array of pieces.)
    $length = count($pieces);
    for ($i = 0; $i < $length; $i++) {
      //print $pieces[$length - $i];
      $slice = array_slice($pieces, 0, $length - $i);
      $path_slice = implode('/', $slice);
      if (file_exists($path_slice)) {
        $status = file_check_directory($path_slice, FILE_CREATE_DIRECTORY);
        break;
      }
    }

    // If we go right the way along to the base and still can't create a directory...
    if ($i == $length) {
      throw new \Exception(strtr("The directory !path cannot be created or is not writable", array(
        '!path' => htmlspecialchars($path_slice, ENT_QUOTES, 'UTF-8'),
      )));
    }
    // print "status: $status for $path_slice - i: $i\n";

    // Now work back down (or in other words, along the array of pieces).
    for ($j = $length - $i; $j < $length; $j++) {
      $slice[] = $pieces[$j];
      $path_slice = implode('/', $slice);
      //print "$path_slice\n";
      $status = file_check_directory($path_slice, FILE_CREATE_DIRECTORY);
    }

    if (!$status) {
      throw new \Exception("The hooks directory cannot be created or is not writable.");
    }
  }