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('/')]