深度阅读

How to remove a directory in Python using os.rmdir() or shutil.rmtree()?

作者
作者
2023年08月22日
更新时间
9.97 分钟
阅读时间
0
阅读量

To remove a directory in Python, you can use either the os.rmdir() or the shutil.rmtree() function, depending on whether the directory is empty or not.

If the directory to be deleted is empty, you can use os.rmdir(path) to remove it:

import os

dir_path = '/path/to/empty_directory'
if os.path.exists(dir_path):
    os.rmdir(dir_path)

If the directory has contents and needs to be deleted along with all its contents, you can use shutil.rmtree(path) to remove it:

import shutil

dir_path = '/path/to/non_empty_directory'
if os.path.exists(dir_path):
    shutil.rmtree(dir_path)

Note that both functions will raise an exception if the specified directory doesn’t exist, so you may want to check for its existence using os.path.exists(path) beforehand.

Also, be careful when using shutil.rmtree() as it will delete all files and subdirectories of the specified directory. Be sure to double-check your path before calling this function to avoid accidental data loss.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。