You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 FolderA and FolderB exist (and are directories) before processing their contents.
  • Using folder_a.rglob("*.jpg") ensures we still capture all JPG files in FolderA and any subfolders it might have—same for FolderB.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:59:09