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

Xóa toàn bộ cây thư mục không rỗng trong Python (shutil.rmtree)

Để xóa thư mục có chứa file/thư mục con, dùng shutil.rmtree().

Ví dụ

import shutil
shutil.rmtree('my_folder')  # xóa đệ quy toàn bộ

Xóa thư mục rỗng

import os
os.rmdir('empty_folder')  # chỉ xóa nếu rỗng, ngược lại ném OSError

Xóa file đơn lẻ

os.remove('file.txt')
# hoặc
os.unlink('file.txt')

Xóa an toàn (bỏ qua lỗi)

shutil.rmtree('my_folder', ignore_errors=True)
# hoặc
import contextlib
with contextlib.suppress(FileNotFoundError):
    shutil.rmtree('my_folder')

Python 3.12+: shutil.rmtree với onexc

def handle_error(func, path, exc_info):
    print(f"Lỗi {func} tại {path}: {exc_info}")

shutil.rmtree('my_folder', onexc=handle_error)