python删除文件夹ch
时间: 2024-05-07 13:21:45 浏览: 51
你可以使用Python的os模块中的rmdir()函数来删除一个空文件夹。这是一个示例代码:
```
import os
# 指定要删除的文件夹路径
folder_path = '/path/to/folder'
try:
# 使用os.rmdir()函数删除文件夹
os.rmdir(folder_path)
print(f"The folder {folder_path} has been deleted successfully.")
except OSError as e:
print("Error: %s : %s" % (folder_path, e.strerror))
```
需要注意的是,如果要删除的文件夹不为空,那么使用os.rmdir()函数会抛出OSError异常。此时可以使用shutil模块中的rmtree()函数来递归删除整个文件夹及其内容。例如:
```
import shutil
# 指定要删除的文件夹路径
folder_path = '/path/to/folder'
try:
# 使用shutil.rmtree()函数递归删除文件夹及其内容
shutil.rmtree(folder_path)
print(f"The folder {folder_path} has been deleted successfully.")
except OSError as e:
print("Error: %s : %s" % (folder_path, e.strerror))
```
需要注意的是,使用shutil.rmtree()函数会彻底删除文件夹及其内容,因此要慎重使用。
阅读全文
相关推荐













