如何修改Pathlib代码,批量遍历指定匹配子目录中的文件?
Solution
Here's how you can adjust your code to target only FolderA and FolderB under each of your main directories:
import pathlib root = "/path/to/your/main/directory" # Replace with your actual root path p = pathlib.Path(root) # Iterate through each main folder first for main_folder in p.iterdir(): if not main_folder.is_dir(): continue # Skip any files in the root directory # Check for FolderA and process its files folder_a = main_folder / "FolderA" if folder_a.exists() and folder_a.is_dir(): for img_file in folder_a.rglob("*.jpg"): # Do something for each image file in FolderA print(f"Processing: {img_file}") # Check for FolderB and process its files folder_b = main_folder / "FolderB" if folder_b.exists() and folder_b.is_dir(): for img_file in folder_b.rglob("*.jpg"): # Do something for each image file in FolderB print(f"Processing: {img_file}")
Key Changes Explained:
- We first loop through each item in your root directory with
p.iterdir(), and skip any non-directory items to focus only on your main folders. - For each main folder, we explicitly check if
FolderAandFolderBexist (and are directories) before processing their contents. - Using
folder_a.rglob("*.jpg")ensures we still capture all JPG files inFolderAand any subfolders it might have—same forFolderB.
If you want a more concise approach (making it easier to add/remove target subfolders later), you can use this version:
import pathlib root = "/path/to/your/main/directory" p = pathlib.Path(root) target_subfolders = {"FolderA", "FolderB"} for main_folder in p.iterdir(): if not main_folder.is_dir(): continue for subfolder_name in target_subfolders: subfolder = main_folder / subfolder_name if subfolder.exists() and subfolder.is_dir(): for img_file in subfolder.rglob("*.jpg"): # Do something for each image file print(f"Processing: {img_file}")
内容的提问来源于stack exchange,提问作者Peter Connolly
相关产品推荐
相关产品推荐

