Python如何搜索目录名中的特定字符串并生成匹配路径列表
How to find directories containing a specific string and collect their paths in Python
If you need to locate all directories whose names include a specific substring (like "04DEM") and gather their full paths for subsequent file processing, here are two reliable approaches using Python's standard libraries:
Using the os module (classic approach)
The os.walk() function recursively traverses directories, making it easy to check each directory name against your target substring.
import os # Define your root directory and target substring root_directory = r"C:\directory" target_substring = "04DEM" matching_directories = [] # Traverse all directories starting from the root for current_path, subdirectories, _ in os.walk(root_directory): for dir_name in subdirectories: # Check if the directory name contains the target substring if target_substring in dir_name: # Build the full path to the matching directory full_dir_path = os.path.join(current_path, dir_name) # Add a trailing directory separator to match your example output full_dir_path_with_slash = os.path.join(full_dir_path, "") matching_directories.append(full_dir_path_with_slash) # Print the results print("Matching directories:") for dir_path in matching_directories: print(dir_path)
Key details:
os.walk()returns three values for each directory: the current path, list of subdirectories, and list of files. We ignore the files with_.os.path.join()safely constructs paths across operating systems. Adding an empty string to the join ensures a trailing slash (likeC:\directory\NewZealand\04DEM\).- For case-insensitive matching, modify the condition to:
if target_substring.lower() in dir_name.lower()
Using pathlib (modern, object-oriented approach)
Python 3.4+ includes pathlib, which offers a cleaner, more readable way to handle file system paths.
from pathlib import Path import os root_directory = Path(r"C:\directory") target_substring = "04DEM" # Recursively search all directories and collect matches matching_directories = [ str(dir_path) + os.sep for dir_path in root_directory.rglob("*") if dir_path.is_dir() and target_substring in dir_path.name ] # Print the results print("Matching directories:") for dir_path in matching_directories: print(dir_path)
Key details:
root_directory.rglob("*")recursively finds all items under the root directory.dir_path.is_dir()ensures we only consider directories, not files.dir_path.namegives the name of the directory (without the full path), which we check for the target substring.- Adding
os.sepappends the appropriate directory separator (backslash on Windows, slash on Unix) to match your example output.
Processing files in the matching directories
Once you have your list of target directories, you can easily process the files inside (e.g., .tif files):
# Using os module for dir_path in matching_directories: for filename in os.listdir(dir_path): file_path = os.path.join(dir_path, filename) if os.path.isfile(file_path) and filename.endswith(".tif"): # Replace with your processing logic print(f"Processing file: {file_path}") # Using pathlib for dir_path_str in matching_directories: dir_path = Path(dir_path_str) for tif_file in dir_path.glob("*.tif"): # Replace with your processing logic print(f"Processing file: {tif_file}")
This will ensure you only work with files located in your target directories, as requested.
内容的提问来源于stack exchange,提问作者Rose
相关产品推荐
相关产品推荐

