如何使用 Python 删除目录?
programmingpythonserver side programming更新于 2025/3/22 16:44:17
可以使用 Python 的内置模块和函数删除目录和文件。删除文件或目录是一个重要的过程,因为在销毁目录后,很难恢复其内容。因此,用户可以通过应用一些有用的 Python 函数轻松删除目录及其内容。
Python 具有以下用于删除目录或文件夹的函数 -
使用 os.rmdir() 函数
Python 使用 os.rmdir() 函数删除空目录。在这种情况下,所需目录必须为空;否则,将引发 OSError。如果目录不存在,则抛出 FileNOtFoundError。
示例
以下是使用 os.rmdir() 函数删除目录的示例 -
import os path = 'C:\Users\Lenovo\Downloads\New folder' try: os.rmdir(path) print("directory is deleted") except OSError as x: print("Error occured: %s : %s" % (path, x.strerror))
输出
以下是上述代码的输出 -
directory is deleted
"path"变量将保存您要删除的目录的路径。
使用 pathlib 模块
Path.rmdir() 函数还可以通过包含 pathlib 模块来帮助删除空目录。
示例
以下是使用 path.rmdir() 函数删除目录的示例 -
from pathlib import Path path= Path('C:\Users\Lenovo\Downloads\New folder') try: path.rmdir() print("Directory is removed successfully") except OSError as x: print("Error occured: %s : %s" % (path, x.strerror))
输出
以下是上述代码的输出 -
Directory is removed successfully
要删除的目录的路径存储在 path 变量中。
使用shutil.rmtree() 函数
您可以使用shutil.rmtree() 函数从系统中删除或移除所需目录及其内容。因此,要删除目录树,请使用shutil 模块。
示例
以下是使用shutil.rmtree() 函数删除目录的示例:−
import shutil path = 'C:\Users\Lenovo\Downloads\Work TP' try: shutil.rmtree(path) print("directory is removed successfully") except OSError as x: print("Error occured: %s : %s" % (path, x.strerror))
输出
以下是上述代码的输出 -
directory is removed successfully
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

