Ask Your Question
4

What is the method to obtain all direct subfolders in Python?

asked 2022-01-30 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-11-09 14:00:00 +0000

djk gravatar image

You can use the os module in Python to obtain all direct subfolders of a given directory using the os.listdir() method. Here is an example:

import os

path = '/path/to/folder'

subfolders = [f.path for f in os.scandir(path) if f.is_dir()]

This will return a list of all subfolders within the specified directory. If you want only the names of the subfolders rather than their full paths, you can modify the list comprehension as follows:

subfolders = [f.name for f in os.scandir(path) if f.is_dir()]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-30 11:00:00 +0000

Seen: 5 times

Last updated: Nov 09 '21