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
ContractsandOther Documentsalready 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
printstatement to use parentheses (your original code uses Python 2 syntax). If you're still on Python 2, you can revert that line toprint filepath. os.makedirswithexist_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.joinensures your script works across all operating systems (Windows, macOS, Linux) without hardcoding path separators like/or\.
内容的提问来源于stack exchange,提问作者Dylan Logan
相关产品推荐
相关产品推荐

