How to List All Sub Directories in a Directory

Getting a list of all subdirectories in the current directory

Do you mean immediate subdirectories, or every directory right down the tree?

Either way, you could use os.walk to do this:

os.walk(directory)

will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so

[x[0] for x in os.walk(directory)]

should give you all of the subdirectories, recursively.

Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.

However, you could use it just to give you the immediate child directories:

next(os.walk('.'))[1]

Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at "How to get all of the immediate subdirectories in Python".

how to list all sub directories in a directory

Use Directory.GetDirectories to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.

var directories = Directory.GetDirectories("your_directory_path");

By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.


Avoiding an UnauthorizedAccessException

It's easily possible that you'll get an UnauthorizedAccessException if you hit a directory to which you don't have access.

You may have to create your own method that handles the exception, like this:

public class CustomSearcher
{
public static List<string> GetDirectories(string path, string searchPattern = "*",
SearchOption searchOption = SearchOption.AllDirectories)
{
if (searchOption == SearchOption.TopDirectoryOnly)
return Directory.GetDirectories(path, searchPattern).ToList();

var directories = new List<string>(GetDirectories(path, searchPattern));

for (var i = 0; i < directories.Count; i++)
directories.AddRange(GetDirectories(directories[i], searchPattern));

return directories;
}

private static List<string> GetDirectories(string path, string searchPattern)
{
try
{
return Directory.GetDirectories(path, searchPattern).ToList();
}
catch (UnauthorizedAccessException)
{
return new List<string>();
}
}
}

And then call it like this:

var directories = CustomSearcher.GetDirectories("your_directory_path");

This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.

How to get list of subdirectories names

I usually check for directories, while assembling a list in one go. Assuming that there is a directory called foo, that I would like to check for sub-directories:

import os
output = [dI for dI in os.listdir('foo') if os.path.isdir(os.path.join('foo',dI))]

Python list directory, subdirectory, and files

Use os.path.join to concatenate the directory and file name:

for path, subdirs, files in os.walk(root):
for name in files:
print(os.path.join(path, name))

Note the usage of path and not root in the concatenation, since using root would be incorrect.


In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join would be:

pathlib.PurePath(path, name)

The advantage of pathlib is that you can use a variety of useful methods on paths. If you use the concrete Path variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.

How to list directories, sub-directories and all files in php

Use scandir to see all stuff in the directory and is_file to check if the item is file or next directory, if it is directory, repeat the same thing over and over.

So, this is completely new code.

function listIt($path) {
$items = scandir($path);

foreach($items as $item) {

// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
echo "-> " . $item . "<br>";
} else {
// this is the directory

// do the list it again!
echo "---> " . $item;
echo "<div style='padding-left: 10px'>";
listIt($path . $item . "/");
echo "</div>";
}
}
}
}

echo "<div style='padding-left: 10px'>";
listIt("/");
echo "</div>";

You can see the live demo here in my webserver, btw, I will keep this link just for a second

When you see the "->" it's an file and "-->" is a directory

The pure code with no HTML:

function listIt($path) {
$items = scandir($path);

foreach($items as $item) {
// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
// Code for file
} else {
// this is the directory
// do the list it again!
// Code for directory
listIt($path . $item . "/");
}
}
}
}

listIt("/");

the demo can take a while to load, it's a lot of items.

PHP Get all subdirectories of a given directory

Option 1:

You can use glob() with the GLOB_ONLYDIR option.

Option 2:

Another option is to use array_filter to filter the list of directories. However, note that the code below will skip valid directories with periods in their name like .config.

$dirs = array_filter(glob('*'), 'is_dir');
print_r($dirs);

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

Then in :gn, g sorts by folders and then files, and n puts those files in alphabetical order.

How to find sub-directories in a directory/folder?

You can use String[] directories = file.list() to list all file names,
then use loop to check each sub-files and use file.isDirectory() function to get subdirectories.

For example:

File file = new File("C:\\Windows");
String[] names = file.list();

for(String name : names)
{
if (new File("C:\\Windows\\" + name).isDirectory())
{
System.out.println(name);
}
}

List all folders and subfolders in cmd, but not the files

Yes, this is possible as it can be read on running in a command prompt window dir /? which outputs the help for command DIR.

dir D:\Movies\* /AD /B /ON /S

This command outputs

  • only directories because of /AD (attribute directory) including those with hidden attribute set,
  • with only the names of the directories because of /B (bare format),
  • with all subdirectories in a directory sorted by name because of /ON (order by name)
  • of specified directory D:\Movies and all subdirectories because of /S and
  • with full path of each directory also because of /S.

A small modification of the command line is needed to ignore directories with hidden attribute set:

dir D:\Movies\* /AD-H /B /ON /S

-H after /AD results in ignoring hidden directories.

See also:

  • Microsoft's command-line reference
  • SS64.com - A-Z index of the Windows CMD command line


Related Topics



Leave a reply



Submit