How to get the names of all directories within a specific directory using python ?


A way to use Python to obtain the names of all directories within a particular directory is by utilizing the listdir() method that is already available:

Using listdir() method

First, we need to import the python os library and then using its built in method listdir() to get a list of all the directories within the directory located at the path specified by you (for example here '/Volumes/HD1/Datasets/2019'):

import os

target_directory = '/Volumes/HD1/Datasets/2019'

directories = os.listdir( target_directory )

Then we can loop through this list of directories, printing out each directory name one by one.

for directory in directories:
    print(directory)

returns for example:

.DS_Store
20190720
20190721
20190722
20190723

Additional features

Remove a given directory from directories

It appears in the example above that there is a directory named '.DS_Store' that we do not want. To remove it from the list of directories, you can use the remove method like this:

Change directory names

Here's an example code snippet that demonstrates how to use the Python os.system() method for changing directory names:

import os

target_directory = '/Volumes/HD1/Datasets/2019'

directories = os.listdir( target_directory )

directories.remove('.DS_Store')

for directory in directories:

    print(directory)

    year = directory[0:4]
    month = directory[4:6]
    day = directory[6:8]

    old_directory = '{}/{}'.format(target_directory,directory)
    new_directory = '{}/{}_{}_{}'.format(target_directory,year,month,day)

    cmd = 'mv {} {}'.format(old_directory,new_directory)

    os.system(cmd)

The code uses the os.system() method to execute a system command that changes the directory name from old_directory to new_directory. This is accomplished using the mv command, which is the standard Unix command for moving or renaming files and directories.

References

Links Site
listdir docs.python.org
remove() docs.python.org
os.system docs.python.org