How can I write a function which lists all files in a directory, including all files in all possible subdirectories?
For example, if the initial directory is /example
, how can I get a list of all files inside this directory, and all subdirectories of /example
, recursively?
The directory names themselves should not be included, only files.
Here is one possible approach based on os.scandir
.
import os
def get_list_of_files_in_directory(dirname: str):
files = []
for f in os.scandir(dirname):
if f.is_dir():
files.extend(get_list_of_files_in_directory(f.path))
if f.is_file():
files.append(f.path)
return files
def main():
base_path = '/example'
files = get_list_of_files_in_directory(base_path)
for file in files:
print(f'found file {file}')
It will list all files in a directory, and all subdirectories of that directory, not including the directories themselves.