Is there a way to get subdirectories in Python without having to iterate over all files?

I am looking for a way to list the subdirectories contained in the current working directory, however I could not find a way that does not iterate over all files.

Basically, if I have a folder with a lot of files and 2 folders, I need a method that can quickly return a list containing the names of the two folders, without having to scan all files as well.

Is there a way to do this in Python?

Edit: I should clarify that my question is about the performance of retrieving directories. I already know several ways to get directories, but they all get slower if there are a bunch of files in the working directory.

+3


source to share


2 answers


You cannot only restore directories from the operating system. You must filter the results. Although it seems that using it os.scandir

improves performance by an order of magnitude (see benchmarks) older os.listdir

and older implementation os.walk

, as it avoids getting anything other than metadata where possible. If you are using 3.5, it is already integrated into the standard library. Otherwise, it looks like you need to use the scandir package .

To filter results from os.scandir



ds = [e.name() for e in os.scandir('.') if e.is_dir()]

      

According to the documentation, it walk

is implemented in terms scandir

that also gives the same speedup.

+1


source


Not sure if there are any direct standard functions out there that will do this for you. But it can be used for this os.walk()

, each iteration os.walk()

returns a format tuple -

(dirpath, dirnames, filenames)

      

Where dirpath

is the current directory, dirnames contains directories inside dirpath

and filenames

contains files inside it.

You can simply call next(os.walk())

to get the above tuple for a directory, then the second element (index - 1) in that tuple will be subfolders inside the directory.



Code -

direcs = next(os.walk('.'))[1]

      

direcs

at the end there will be a list of subfolders of the current folder. You can also specify a different folder to get a list of folders within it.

+2


source







All Articles