0

I'm building a music player using Python and I have this scandir-like function that returns a list of all folders with music in them.

The result looks something like this:

folders = [
    "~/Music/",
    "~/Music/Band On The Run (Standard)",
    "~/Music/The life - Frank Sinatra",
    "~/Music/Link to Music",
    "~/Music/Link to Music/100 Dolly Parton",
    "~/Music/Link to Music/JW-Unreleased/Fighting Demons",
    "~/Music/Link to Music/JW-Unreleased/Goodbye and Good Riddance",
    # a million more items
]

The scandir-like function is quite expensive because it checks the whole user drive and takes an inconsistent amount of time.

Due to the inconsistencies, I want to run the function periodically in the background and use the result for the next 5 minutes.

I want to create a function that will return all sub-directories of a folder using the folders list above. For example, if I pass "~/Music/" to the function then I can get a list containing all the immediate sub-folders within it without using scandir():

def get_children(parent:str) -> List:
    subfolders = []

    # do something

    return subfolders

get_children("~/Music/")

# ["Band On The Run (Standard)", "The life - Frank Sinatra", "Link to Music"]

How can I implement such a function?

  • Why don't you use the [os.walk](https://www.tutorialspoint.com/python3/os_walk.htm) or [os.listdir](https://www.geeksforgeeks.org/python-os-listdir-method/) methods? – chill0r Mar 22 '22 at 08:27
  • I recommend using [`Path.glob('**/*')`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob). See this [answer](https://stackoverflow.com/a/63803905/355230). – martineau Mar 22 '22 at 08:45

0 Answers0