杰瑞科技汇

Python如何判断目录?

Of course! The question "python is directory" can be interpreted in a few ways. I'll cover the most common ones:

Python如何判断目录?-图1
(图片来源网络,侵删)
  1. How to check if a path is a directory in Python. (This is the most likely question)
  2. How to list the contents of a directory.
  3. How to create a new directory.

Let's break them down with clear code examples.


How to Check if a Path is a Directory

This is the most direct answer to your question. You need to use Python's built-in pathlib module (modern and recommended) or the os module (classic).

Method 1: Using pathlib (Recommended)

The pathlib module provides an object-oriented way to interact with filesystem paths. It's generally considered more readable and modern.

from pathlib import Path
# Define the path you want to check
path_to_check = Path('/usr/bin') # A known directory
path_to_check_file = Path('/etc/hosts') # A known file
path_to_check_nonexistent = Path('/this/path/does/not/exist')
# Use the .is_dir() method to check
print(f"Is {path_to_check} a directory? {path_to_check.is_dir()}")
# Output: Is /usr/bin a directory? True
print(f"Is {path_to_check_file} a directory? {path_to_check_file.is_dir()}")
# Output: Is /etc/hosts a directory? False
print(f"Is {path_to_check_nonexistent} a directory? {path_to_check_nonexistent.is_dir()}")
# Output: Is /this/path/does/not/exist a directory? False

Method 2: Using the os Module

The os module is the traditional way to interact with the operating system. It's still very common and useful.

Python如何判断目录?-图2
(图片来源网络,侵删)
import os
# Define the path you want to check
path_to_check = '/usr/bin'
path_to_check_file = '/etc/hosts'
path_to_check_nonexistent = '/this/path/does/not/exist'
# Use os.path.isdir() to check
print(f"Is {path_to_check} a directory? {os.path.isdir(path_to_check)}")
# Output: Is /usr/bin a directory? True
print(f"Is {path_to_check_file} a directory? {os.path.isdir(path_to_check_file)}")
# Output: Is /etc/hosts a directory? False
print(f"Is {path_to_check_nonexistent} a directory? {os.path.isdir(path_to_check_nonexistent)}")
# Output: Is /this/path/does/not/exist a directory? False

How to List the Contents of a Directory

Once you know a path is a directory, you'll often want to see what's inside it.

Method 1: Using pathlib (Recommended)

The Path object has a .iterdir() method that returns an iterator of all the items (files and directories) in that path.

from pathlib import Path
# Get a Path object for the current directory
current_dir = Path('.')
print(f"Contents of {current_dir.resolve()}:")
print("-" * 20)
# Loop through the items
for item in current_dir.iterdir():
    # Use .is_dir() to print [DIR] or [FILE]
    item_type = "[DIR]" if item.is_dir() else "[FILE]"
    print(f"{item_type.ljust(6)} {item.name}")

Method 2: Using the os Module

The os module provides os.listdir() which returns a list of all filenames in the given path.

import os
# Get a list of filenames in the current directory
contents = os.listdir('.')
print(f"Contents of the current directory:")
print("-" * 20)
# Loop through the filenames
for filename in contents:
    # Construct the full path to check if it's a directory
    full_path = os.path.join('.', filename)
    item_type = "[DIR]" if os.path.isdir(full_path) else "[FILE]"
    print(f"{item_type.ljust(6)} {filename}")

How to Create a New Directory

You might also need to create a directory. Here's how to do that safely.

Python如何判断目录?-图3
(图片来源网络,侵删)

Method 1: Using pathlib (Recommended)

The Path object has a .mkdir() method.

  • path.mkdir(): Creates a single directory. Fails if the parent directory doesn't exist.
  • path.mkdir(parents=True): Creates the directory and any necessary parent directories. Very useful!
from pathlib import Path
import os # To check if it exists before creating
# Create a single directory
new_dir = Path('./my_new_folder')
if not new_dir.exists():
    new_dir.mkdir()
    print(f"Created directory: {new_dir}")
else:
    print(f"Directory {new_dir} already exists.")
# Create a nested directory structure
nested_dir = Path('./data/2025/reports')
if not nested_dir.exists():
    nested_dir.mkdir(parents=True) # The 'parents=True' is key here!
    print(f"Created nested directories: {nested_dir}")
else:
    print(f"Directory {nested_dir} already exists.")

Method 2: Using the os Module

The os module provides os.mkdir() and os.makedirs().

  • os.mkdir(path): Creates a single directory. Fails if the parent directory doesn't exist.
  • os.makedirs(path, exist_ok=True): Creates the directory and any necessary parent directories. The exist_ok=True argument prevents an error if the directory already exists.
import os
# Create a single directory
new_dir = './my_new_folder_os'
if not os.path.exists(new_dir):
    os.mkdir(new_dir)
    print(f"Created directory: {new_dir}")
else:
    print(f"Directory {new_dir} already exists.")
# Create a nested directory structure
nested_dir = './data/2025/reports'
if not os.path.exists(nested_dir):
    os.makedirs(nested_dir) # makedirs is the equivalent of mkdir(parents=True)
    print(f"Created nested directories: {nested_dir}")
else:
    print(f"Directory {nested_dir} already exists.")

Summary: pathlib vs. os

Task pathlib (Modern) os (Classic)
Check if a path is a directory Path('my_dir').is_dir() os.path.isdir('my_dir')
List directory contents Path('.').iterdir() os.listdir('.')
Create a single directory Path('my_dir').mkdir() os.mkdir('my_dir')
Create nested directories Path('a/b/c').mkdir(parents=True) os.makedirs('a/b/c')

For new code, pathlib is highly recommended due to its clarity and object-oriented approach. However, you will still see os used everywhere in existing codebases.

分享:
扫描分享到社交APP
上一篇
下一篇