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

Python脚本实现:遍历目录并创建缺失的指定子文件夹

完成你的Python文件夹检查与创建脚本

Hey Dylan, nice work getting the initial loop set up! Let's build out the rest of the functionality to check for and create those required subfolders.

关键补充步骤

Your current code already iterates through subfolders in the current directory. Now we need to:

  • For each subfolder, check if Contracts and Other Documents already exist
  • Create the folders if they're missing

完整实现代码

Here's the updated script with all the pieces put together (I've added comments to explain each new part, and adjusted for Python 3 compatibility):

import os

# Define the required subfolders
folders_to_be_made = ['Contracts', 'Other Documents']

# Iterate through all items in the current directory
for folder in os.listdir('.'):
    folder_path = os.path.join(os.getcwd(), folder)
    # Only process directories (skip files)
    if os.path.isdir(folder_path):
        print(f"Checking folder: {folder_path}")
        # Loop through each required subfolder
        for subfolder in folders_to_be_made:
            # Build the full path to the subfolder
            subfolder_path = os.path.join(folder_path, subfolder)
            # Check if the subfolder doesn't exist
            if not os.path.isdir(subfolder_path):
                # Create the subfolder - exist_ok=True prevents errors if it's created mid-script by another process
                os.makedirs(subfolder_path, exist_ok=True)
                print(f"Created missing subfolder: {subfolder_path}")
            else:
                print(f"Subfolder already exists: {subfolder_path}")

重要细节说明

  • Python 3 Compatibility: I updated the print statement to use parentheses (your original code uses Python 2 syntax). If you're still on Python 2, you can revert that line to print filepath.
  • os.makedirs with exist_ok=True: This ensures the script doesn't throw an error if the folder gets created between the check and creation step (a common edge case in multi-process environments).
  • Path Construction: Using os.path.join ensures your script works across all operating systems (Windows, macOS, Linux) without hardcoding path separators like / or \.

内容的提问来源于stack exchange,提问作者Dylan Logan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:12:58