How to get all of the immediate subdirectories in Python
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 How To Get All Of The Immediate Subdirectories In Python
00:19 Answer 1 Score 255
00:27 Answer 2 Score 21
00:46 Answer 3 Score 79
01:09 Answer 4 Score 44
01:21 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
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 How To Get All Of The Immediate Subdirectories In Python
00:19 Answer 1 Score 255
00:27 Answer 2 Score 21
00:46 Answer 3 Score 79
01:09 Answer 4 Score 44
01:21 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)