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".
Getting a list of all subdirectories in the current directory and ignoring directories with no reading permission
following code skips those files you cant access due perms
abs_file_paths=[os.path.join(root, file) for root, dir, files in os.walk(dir_to_extract) for file in files]
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))]
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.
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);
How to get folders list from the current dir and not subdirectories?
os.walk('/tmp/').next()[1]
lists all the folders inside the current directory
for folder in os.walk('/tmp/').next()[1]:
print folder
Python folder names in the directory
You can use os.walk()
# !/usr/bin/python
import os
directory_list = list()
for root, dirs, files in os.walk("/path/to/your/dir", topdown=False):
for name in dirs:
directory_list.append(os.path.join(root, name))
print directory_list
EDIT
If you only want the first level and not actually "walk" through the subdirectories, it is even less code:
import os
root, dirs, files = os.walk("/path/to/your/dir").next()
print dirs
This is not really what os.walk
is made for. If you really only want one level of subdirectories, you can also use os.listdir()
like Yannik Ammann suggested:
root='/path/to/my/dir'
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print dirlist
How to get a list of all folders in an entire drive
os.walk
yields three-tuple
s for each directory traversed, in the form (currentdir, containeddirs, containedfiles)
. This listcomp:
[x[0] for x in os.walk(directory)]
just ignores the contents of each directory and just accumulates the directories it enumerates. It would be slightly nicer/more self-documenting if written with unpacking (using _
for stuff you don't care about), e.g.:
dirs = [curdir for curdir, _, _ in os.walk(directory)]
but they're both equivalent. To make it list for the entire drive, just provide the root of the drive as the directory
argument to os.walk
, e.g. for Windows:
c_drive_dirs = [curdir for curdir, _, _ in os.walk('C:\\')]
or for non-Windows:
alldirs = [curdir for curdir, _, _ in os.walk('/')]
How do I get the list of all items in dir1 which don't exist in dir2?
You can use comm
to compare two listings:
comm -23 <(ls dir1) <(ls dir2)
- process substitution with
<(cmd)
passes the output ofcmd
as if it were a file name. It's similar to$(cmd)
but instead of capturing the output as a string it generates a dynamic file name (usually/dev/fd/###
). comm
prints three columns of information: lines unique to file 1, lines unique to file 2, and lines that appear in both.-23
hides the second and third columns and shows only lines unique to file 1.
You could extend this to do a recursive diff using find
. If you do that you'll need to suppress the leading directories from the output, which can be done with a couple of strategic cd
s.
comm -23 <(cd dir1; find) <(cd dir2; find)
Related Topics
Python List by Value Not by Reference
Equivalent to Gettickcount() on Linux
What Is the Easiest Way to Detect Key Presses in Python 3 on a Linux MAChine
Python: What Are the Nearest Linux and Osx Equivalents of Winsound.Beep
Trying to Import Pypyodbc Module Gives Error 'Odbc Library Is Not Found. Is Ld_Library_Path Set'
How to Default Python3.8 on My MAC Using Homebrew
How to Get a Process's Stdin by a Process Id
Histogram of an Image's "Black Ink Level" by Horizontal Axis
How to Limit the Amount of Time a Function Can Run for (Add a Timeout)
Python Requests Json Returns Single Quote
Pytesseract Ocr Multiple Config Options
How to Find the Owner of a File or Directory in Python
Getting Another Program's Output as Input on the Fly
How to Properly Write to Fifos in Python
How to Programmatically Edit Excel Sheets
How to Find Out the Date of the Last Saturday in Linux Shell Script or Python