乐闻世界logo
搜索文章和话题

How can I find all of the distinct file extensions in a folder hierarchy?

1个答案

1

In a folder hierarchy, finding all unique file extensions can be achieved by writing a script. Python is particularly well-suited for this task as it offers robust libraries for handling files and directories. Below are specific steps and example code:

Step 1: Import necessary libraries

First, import the os module, which provides various functions for interacting with the operating system, including traversing directories and files.

python
import os

Step 2: Set the directory to traverse

You can set the path of the folder to search as a variable, for example:

python
folder_path = '/path/to/your/folder'

Step 3: Traverse the directory and collect file extensions

Use the os.walk() function to traverse the directory. This function generates file names and subdirectory names within the folder. For each file, extract the file extension and store it in a set (sets automatically handle duplicates).

python
def find_unique_extensions(folder_path): extensions = set() for root, dirs, files in os.walk(folder_path): for file in files: extension = os.path.splitext(file)[1] if extension: extensions.add(extension) return extensions

Step 4: Print or return the unique file extensions

Finally, you can print or use these extensions in other ways:

python
unique_extensions = find_unique_extensions(folder_path) print("Unique file extensions:", unique_extensions)

Example Illustration:

Assume a directory /path/to/your/folder containing files with extensions .txt, .jpg, .py, and .mp3. Running the above script will output:

shell
Unique file extensions: {'.txt', '.jpg', '.py', '.mp3'}

This approach is concise and effective, allowing you to quickly retrieve all unique file extensions within a folder and its subfolders. If further operations on these extensions are needed (e.g., counting the number of files per extension), you can extend this script accordingly.

2024年8月16日 23:26 回复

你的答案