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

基于os模块创建目录与子目录的Python代码优化问询

Hey there! Let's break down how to fix that hardcoding issue and make your directory creation function way more flexible and maintainable. Here are the key improvements we can make:

1. Extract Hardcoded Root Path as a Parameter

Right now your root path (C:\path\to\destination\) is baked into the function. Turning it into a parameter lets you reuse the function for different destinations without editing the core code.

2. Ditch Manual Path Concatenation

String-concatenating paths is error-prone (especially with slashes across OSes). Use os.path.join() or the modern pathlib module to handle path construction cleanly.

3. Simplify Creation with exist_ok=True

The os.makedirs() (and pathlib.Path.mkdir()) functions have an exist_ok=True flag that skips redundant existence checks. This eliminates most of your try-except blocks while safely handling pre-existing directories.

4. Make Directory Structures Configurable

Hardcoding folder lists like ["Stats","Press","Info"] makes changes a hassle. Define these as top-level constants or optional parameters so you can adjust the structure quickly.

5. Use pathlib for Modern, Clean Code

Python 3.4+ includes pathlib, which uses object-oriented syntax for paths—making your code more readable and less error-prone.


Optimized Code (Using pathlib)

import os
from pathlib import Path

# Configurable directory structures (easy to modify)
GAME_SUBFOLDERS = ["Stats", "Press", "Info"]
INFO_SUBFOLDERS = ["Before", "After"]

def create_match_dirs(match_date: str, home_team: str, away_team: str, info: str, root_dir: str = r"C:\path\to\destination"):
    # Convert root path to a Path object for intuitive handling
    root_path = Path(root_dir)
    
    # Build all necessary paths with clean syntax
    match_date_path = root_path / match_date
    game_folder_name = f"{home_team} vs {away_team} ({info})"
    game_path = match_date_path / game_folder_name
    info_folder_name = f"Info-Pictures ({info})"
    info_path = match_date_path / info_folder_name
    
    try:
        # Create parent directories (automatically skips existing ones)
        match_date_path.mkdir(exist_ok=True, parents=True)
        
        # Create main game and info folders
        game_path.mkdir(exist_ok=True)
        info_path.mkdir(exist_ok=True)
        
        # Create subfolders inside game directory
        for subfolder in GAME_SUBFOLDERS:
            (game_path / subfolder).mkdir(exist_ok=True)
        
        # Create subfolders inside info directory
        for subfolder in INFO_SUBFOLDERS:
            (info_path / subfolder).mkdir(exist_ok=True)
            
    except OSError as e:
        print(f"Error creating directories: {str(e)}")

Key Improvements in This Version:

  • No hardcoded root path—pass a custom path when calling, or use the default
  • pathlib uses / to join paths, which is far cleaner than string concatenation
  • exist_ok=True handles all existence checks automatically, removing redundant try-except blocks
  • Configurable folder lists at the top make adjustments trivial
  • Descriptive variable names (like match_date_path instead of newpath) improve readability
  • Type hints clarify expected input types for future you or other developers

For Python <3.4 (Using os.path)

If you're stuck on an older Python version, here's a similar optimized version:

import os

GAME_SUBFOLDERS = ["Stats", "Press", "Info"]
INFO_SUBFOLDERS = ["Before", "After"]

def create_match_dirs(match_date, home_team, away_team, info, root_dir=r"C:\path\to\destination"):
    # Build paths with os.path.join for cross-OS compatibility
    match_date_path = os.path.join(root_dir, match_date)
    game_folder_name = f"{home_team} vs {away_team} ({info})"
    game_path = os.path.join(match_date_path, game_folder_name)
    info_folder_name = f"Info-Pictures ({info})"
    info_path = os.path.join(match_date_path, info_folder_name)
    
    try:
        # Create directories with exist_ok=True to skip existence checks
        os.makedirs(match_date_path, exist_ok=True)
        os.makedirs(game_path, exist_ok=True)
        os.makedirs(info_path, exist_ok=True)
        
        # Create game subfolders
        for subfolder in GAME_SUBFOLDERS:
            os.makedirs(os.path.join(game_path, subfolder), exist_ok=True)
        
        # Create info subfolders
        for subfolder in INFO_SUBFOLDERS:
            os.makedirs(os.path.join(info_path, subfolder), exist_ok=True)
            
    except OSError as e:
        print(f"Error creating directories: {str(e)}")

Extra Tips for Further Improvement:

  • Replace print with logging: For production use, the logging module is more flexible for debugging and monitoring than basic print statements.
  • Add Input Validation: Check that inputs like match_date or home_team aren't empty strings to avoid creating invalid directory names.
  • Return Paths: Modify the function to return the created paths if you need to use them elsewhere in your code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:50:14