在Python中,删除整个文件夹及其内容的方法如下:
使用`os.rmdir()`函数
该函数只能删除空文件夹。如果需要删除非空文件夹,可以使用`shutil.rmtree()`函数。
示例代码:
```python
import os
folder_path = 'path/to/folder'
if os.path.exists(folder_path):
os.rmdir(folder_path)
else:
print("Folder not found")
```
使用`shutil.rmtree()`函数
该函数可以递归删除文件夹及其所有内容,无论文件夹是否为空。
示例代码:
```python
import shutil
folder_path = 'path/to/folder'
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
else:
print("Folder not found")
```
建议
在使用`shutil.rmtree()`函数时,请确保文件夹路径正确,并仔细检查要删除的文件夹,因为该操作是不可逆的。
如果需要删除的文件夹包含重要数据,建议先进行备份,以防万一。