How to get all of the immediate subdirectories in Python
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 How To Get All Of The Immediate Subdirectories In Python
00:22 Answer 1 Score 255
00:35 Accepted Answer Score 162
02:47 Answer 3 Score 79
03:16 Answer 4 Score 44
03:34 Answer 5 Score 21
03:56 Thank you
--
Full question
https://stackoverflow.com/questions/8001...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #file
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 How To Get All Of The Immediate Subdirectories In Python
00:22 Answer 1 Score 255
00:35 Accepted Answer Score 162
02:47 Answer 3 Score 79
03:16 Answer 4 Score 44
03:34 Answer 5 Score 21
03:56 Thank you
--
Full question
https://stackoverflow.com/questions/8001...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #file
#avk47
ANSWER 1
Score 255
import os
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
ANSWER 2
Score 79
Why has no one mentioned glob? glob lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:
from glob import glob
paths = glob('*/')
Note that glob will return the directory with the final slash (as unix would) while most path based solutions will omit the final slash.
ANSWER 3
Score 44
Check "Getting a list of all subdirectories in the current directory".
Here's a Python 3 version:
import os
dir_list = next(os.walk('.'))[1]
print(dir_list)
ANSWER 4
Score 21
import os
To get (full-path) immediate sub-directories in a directory:
def SubDirPath (d):
return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])
To get the latest (newest) sub-directory:
def LatestDirectory (d):
return max(SubDirPath(d), key=os.path.getmtime)