What is the method to delete a folder in Python?

In Python, you can use the rmdir() method from the os module to delete empty folders and the rmtree() method from the shutil module to delete non-empty folders.

Here is an example of removing empty folders.

import os

# 定义要删除的文件夹路径
folder_path = "path/to/folder"

# 删除空文件夹
os.rmdir(folder_path)

Here is an example of deleting a non-empty folder:

import shutil

# 定义要删除的文件夹路径
folder_path = "path/to/folder"

# 删除非空文件夹
shutil.rmtree(folder_path)

It is important to note that the rmtree() method will delete the entire folder and all its contents, including subfolders and files. Therefore, be cautious when using the rmtree() method, and make sure not to accidentally delete important folders.

bannerAds