Last active
February 26, 2024 09:12
-
-
Save francescopapaleo/65db7e16ec592c8155fa1ee68a0f475a to your computer and use it in GitHub Desktop.
Find all files with a given extension in a directory recursively and return a list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def find_files(start_path: str, extensions: List[str] = AUDIO_EXTENSIONS) -> List[str]: | |
| """Finds all audio files in a directory recursively. | |
| Returns a list. | |
| Parameters | |
| ---------- | |
| folder : str | |
| Folder to look for audio files in, recursively. | |
| ext : List[str], optional | |
| Extensions to look for without the ., by default | |
| ``['.wav', '.flac', '.mp3', '.mp4']``. | |
| Returns | |
| ------- | |
| List[str] | |
| List of file paths. | |
| """ | |
| # Ensure extensions are in a consistent format | |
| extensions = [ | |
| ext.lower() if ext.startswith(".") else f".{ext.lower()}" for ext in extensions | |
| ] | |
| matched_files = [] | |
| # Walk through all directories and files starting from start_path | |
| for root, dirs, files in os.walk(start_path): | |
| for file in files: | |
| # Check if the file ends with any of the provided extensions | |
| if any(file.lower().endswith(ext) for ext in extensions): | |
| matched_files.append(os.path.join(root, file)) | |
| # Sort the list of matched files in alphabetical order before returning | |
| return sorted(matched_files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment