Python遍历目录:批量收集指定层级数据文件夹路径至列表
Python Script to Extract Target Folder Paths
Got it, let's solve this problem step by step. Here's a practical Python script that will collect all the Pxxxx folder paths you need, along with clear explanations of how each part works:
import os import re def get_target_paths(): # Define the root directory holding all your "Raw data ####" folders root_dir = r"C:\users\documents\holding_folder" target_paths = [] # Loop through every item in the root directory for entry in os.listdir(root_dir): entry_full_path = os.path.join(root_dir, entry) # Check if the item is a directory and matches the "Raw data ####" pattern if os.path.isdir(entry_full_path): folder_match = re.match(r"Raw data (\d{4})", entry) if folder_match: # Extract the 4-digit number from the folder name four_digit_code = folder_match.group(1) # Build the full path to the target Pxxxx folder target_folder = f"P{four_digit_code}" final_target_path = os.path.join(entry_full_path, "sub", "supersub", target_folder) # Only add the path if it actually exists (avoids missing/incomplete folders) if os.path.exists(final_target_path): target_paths.append(final_target_path) return target_paths # Example usage to test the script if __name__ == "__main__": collected_paths = get_target_paths() print(f"Found {len(collected_paths)} target folders:") for path in collected_paths: print(path)
Key Breakdown of the Script:
- Regex Pattern Matching: The
re.match(r"Raw data (\d{4})", entry)line ensures we only process folders that strictly follow your "Raw data ####" naming convention, and reliably extracts the 4-digit code we need for thePxxxxfolder name. - Safe Path Construction: Using
os.path.join()instead of hardcoding backslashes makes the script more robust (and works across operating systems if you ever need to adapt it). - Existence Check: The
os.path.exists(final_target_path)step filters out any paths where thesub\supersub\Pxxxxstructure is missing, so you don't end up with invalid entries in your list. - Reusable Function: Wrapping the logic in a function makes it easy to call this code from other parts of your project if needed.
If you ever need to adjust this for slight changes in your folder structure (like different subdirectory names), just tweak the regex pattern or the path construction line accordingly.
内容的提问来源于stack exchange,提问作者CandleWax
相关产品推荐
相关产品推荐

