杰瑞科技汇

os.makedirs python

Of course! Let's dive deep into os.makedirs in Python. It's a fundamental and very useful function for working with directories.

os.makedirs python-图1
(图片来源网络,侵删)

What is os.makedirs?

os.makedirs is a function from Python's built-in os module. Its primary purpose is to create a directory, and if necessary, all the intermediate parent directories, in a single operation.

In simple terms, if you want to create a path like project/data/images/, and the project directory doesn't exist, os.makedirs will create project, then project/data, and finally project/data/images for you, all in one go.


Basic Syntax

import os
os.makedirs(name, mode=0o777, exist_ok=False)

Parameters:

  1. name (required): The path of the directory (or directories) you want to create. This can be a string representing either a relative path (e.g., 'new_dir') or an absolute path (e.g., '/home/user/new_dir').

  2. mode (optional): The permissions for the newly created directories. It's an integer representing the permission bits in octal format (e.g., 0o755). This parameter is often ignored on Windows. The default is 0o777 (most permissive).

    os.makedirs python-图2
    (图片来源网络,侵删)
  3. exist_ok (optional, boolean):

    • If False (the default), the function will raise a FileExistsError if the target directory already exists.
    • If True, the function will do nothing if the directory already exists. This is extremely useful for avoiding errors in your scripts.

How it Works: Key Scenarios

Let's explore the different behaviors with examples.

Scenario 1: Creating a Single Directory

If the parent directory already exists, makedirs works just like mkdir.

import os
# We assume the current directory is empty for this example
os.makedirs("my_folder")
# Check if it was created
print(os.listdir()) 
# Output: ['my_folder'] 

Scenario 2: Creating a Nested Directory (The Main Use Case)

This is where makedirs shines. It creates all the necessary parent directories.

os.makedirs python-图3
(图片来源网络,侵删)
import os
# Let's create a nested directory structure
# 'logs', 'app', and 'app/data' will be created if they don't exist
os.makedirs("logs/app/data")
# Check the directory structure
print(os.listdir())
# Output: ['logs']
print(os.listdir("logs"))
# Output: ['app']
print(os.listdir("logs/app"))
# Output: ['data']

Scenario 3: Handling Existing Directories (exist_ok)

This is a critical difference between os.makedirs and the older os.mkdir.

  • With exist_ok=False (Default): If the directory already exists, your script will crash.

    import os
    # First, create the directory
    os.makedirs("existing_dir")
    # Now, try to create it again
    try:
        os.makedirs("existing_dir")
    except FileExistsError as e:
        print(f"Error: {e}")
    # Output: Error: [Errno 17] File exists: 'existing_dir'
  • With exist_ok=True: If the directory already exists, the function does nothing and your script continues without error. This is the recommended approach for most modern applications.

    import os
    # First, create the directory
    os.makedirs("existing_dir_safe")
    # Now, try to create it again. This will not raise an error.
    os.makedirs("existing_dir_safe", exist_ok=True)
    print("Directory exists or was created successfully!")
    # Output: Directory exists or was created successfully!

os.makedirs vs. os.mkdir

This is a common point of confusion.

Feature os.makedirs() os.mkdir()
Purpose Create a directory and all its parent directories. Create a single directory.
Parent Handling Creates parents if they don't exist. Fails if the parent directory does not exist.
Error on Exist Raises FileExistsError by default. Raises FileExistsError by default.
exist_ok Yes, this parameter is available. Yes, this parameter is available (since Python 3.2).

Example of os.mkdir failing:

import os
# This will work
os.mkdir("parent_dir")
# This will work
os.mkdir("parent_dir/child_dir")
# This will FAIL with FileNotFoundError
# because 'another_parent' does not exist.
try:
    os.mkdir("another_parent/another_child_dir")
except FileNotFoundError as e:
    print(f"Error with mkdir: {e}")
# Output: Error with mkdir: [Errno 2] No such file or directory: 'another_parent/another_child_dir'

Best Practices and Modern Alternatives

While os.makedirs is excellent, the modern Python way is to use the pathlib module, which provides an object-oriented interface to filesystem paths.

The pathlib Approach (Recommended)

The equivalent function in pathlib is Path.mkdir().

from pathlib import Path
# Create a Path object
# Note the 'p' suffix is a common convention for Path objects
log_dir_p = Path("logs/app/data")
# Create the directory and all parents
# The 'exist_ok=True' argument works the same way
log_dir_p.mkdir(parents=True, exist_ok=True)
print(f"Directory created/verified at: {log_dir_p}")

Why is pathlib often better?

  • Object-Oriented: You can easily perform other path manipulations (e.g., log_dir_p / "error.log").
  • Cross-Platform: It handles path separators ( vs \) automatically.
  • Readability: The code is often more intuitive and readable.
  • Rich API: It has many useful methods like .exists(), .is_dir(), .read_text(), .write_text(), etc.

A Practical Example: Saving a File to a Nested Path

A very common use case is saving a file to a complex directory structure that might not exist yet.

import os
from pathlib import Path
# --- Using os ---
file_path_os = "results/experiment_1/report.txt"
os.makedirs(os.path.dirname(file_path_os), exist_ok=True)
with open(file_path_os, "w") as f:
    f.write("Report using os module.")
# --- Using pathlib (more concise) ---
file_path_pl = Path("results/experiment_2/report.txt")
file_path_pl.parent.mkdir(parents=True, exist_ok=True)
file_path_pl.write_text("Report using pathlib module.")
print("Both files have been saved.")

Summary

Function When to Use
os.makedirs(name, exist_ok=True) A perfectly fine, built-in way to create directories. Great for simple scripts or if you can't use pathlib. Always use exist_ok=True to prevent crashes.
pathlib.Path(path).mkdir(parents=True, exist_ok=True) The modern, recommended approach. It's more powerful, readable, and robust. Use this for any new project.
分享:
扫描分享到社交APP
上一篇
下一篇