Retrieve File Extensions from Directory Path using Python

Prompt

get file extensions after reading them from certain path.  
Python

Result

import os

def get_file_extensions(path):
    file_extensions = set()
    for root, dirs, files in os.walk(path):
        for file in files:
            file_extension = os.path.splitext(file)[1]
            file_extensions.add(file_extension)
    return file_extensions

path = "/path/to/directory"
extensions = get_file_extensions(path)
print(extensions)
Python

In the above Python code, we import the os module to work with file paths and extensions. We define a function get_file_extensions that takes a path as input. Inside the function, we use the os.walk function to recursively traverse the directory tree rooted at path. For each file encountered, we use os.path.splitext to split the file name and extension, and then add the extension to a set of file extensions. Finally, we return the set of file extensions. We then call the get_file_extensions function with a sample path and print the resulting file extensions.