1

I tried a python code to search all directories inside a main folder in my pc, the code is:

[x[0] for x in os.walk(dir)]

that I found in here.

Well, now I'm interested in writing a similar code able to search and list all available directories in my pc without specifying the main directory 'dir' (suppose I don't know if I'm in C:\, in E:\, in C:\python2.7\, etc...). For 'available' I mean all directories that can be opened/read/modified and are accessible with my account (which has specific privileges that, suppose, I do not know).

Have you some working codes to perform what I ask?

Thank you

Matteo VR
  • 11
  • 5

1 Answers1

0

If you are on Python 3, you have access to pathlib.Path

You have to start at some directory, for example your current working directory. From that, you can get the root of the file system (/ under *n*x, letter:\ under Windows):

import os
import pathlib

root = str(pathlib.Path(os.getcwd()).absolute().root)

all_dirs = [x[0] for x in os.walk(root)]

In Python 2.7 on Windows, you can use os.path.splitdrive to split os.getcwd() into drive letter and path and go from there.

import os

root, path = os.path.splitdrive(os.getcwd())
all_dirs = [x[0] for x in os.walk(root + "/")]

Note that I use / instead of \: Windows supports the use of a forward slash as well, and like this it will also work on other systems (because root will be an empty string there).

L3viathan
  • 26,748
  • 2
  • 58
  • 81