Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra thư mục có chứa thư mục con trong Python

Kiểm tra xem một thư mục có chứa bất kỳ thư mục con nào không.

Cách 1: any() + os.path.isdir

import os

def has_subdir(path):
    return any(os.path.isdir(os.path.join(path, entry)) for entry in os.listdir(path))

print(has_subdir('.'))  # True/False

Cách 2: os.scandir (hiệu quả hơn, Python 3.5+)

def has_subdir_scandir(path):
    with os.scandir(path) as it:
        return any(entry.is_dir() for entry in it)

os.scandir() trả về DirEntry object có sẵn is_dir(), is_file() không cần syscall thêm.

Cách 3: all() — kiểm tra TOÀN BỘ entry đều là file

all_files = all(os.path.isfile(os.path.join('.', f)) for f in os.listdir('.'))
has_subdir = not all_files