How to get all of the immediate subdirectories in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Question
00:27 Accepted answer (Score 141)
02:58 Answer 2 (Score 249)
03:10 Answer 3 (Score 78)
03:42 Answer 4 (Score 42)
04:01 Thank you
--
Full question
https://stackoverflow.com/questions/8001...
Accepted answer links:
https://stackoverflow.com/a/48030307/244...
Answer 3 links:
[glob]: https://docs.python.org/2/library/glob.h...
Answer 4 links:
[Getting a list of all subdirectories in the current directory]: https://stackoverflow.com/questions/9734...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #file
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Question
00:27 Accepted answer (Score 141)
02:58 Answer 2 (Score 249)
03:10 Answer 3 (Score 78)
03:42 Answer 4 (Score 42)
04:01 Thank you
--
Full question
https://stackoverflow.com/questions/8001...
Accepted answer links:
https://stackoverflow.com/a/48030307/244...
Answer 3 links:
[glob]: https://docs.python.org/2/library/glob.h...
Answer 4 links:
[Getting a list of all subdirectories in the current directory]: https://stackoverflow.com/questions/9734...
--
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)