📜  使用Python删除整个目录树 | shutil.rmtree() 方法

📅  最后修改于: 2022-05-13 01:55:19.933000             🧑  作者: Mango

使用Python删除整个目录树 | shutil.rmtree() 方法

Python中的Shutil 模块提供了许多对文件和文件集合进行高级操作的功能。它属于 Python 的标准实用程序模块。该模块有助于自动化复制和删除文件和目录的过程。
shutil.rmtree() 用于删除整个目录树,路径必须指向目录(但不能指向目录的符号链接)。

示例 1:假设目录和子目录如下。
# 父目录:

python shutil.rmtree()

# 父目录内的目录:

python shutil.rmtree()

# 子目录下的文件:

python shutil.rmtree()

我们要删除目录作者。下面是实现。

Python3
# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path)


Python3
# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path, ignore_errors = False)
   
# making ignore_errors = True will not raise 
# a FileNotFoundError


Python3
# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
   
# exception handler
def handler(func, path, exc_info):
    print("Inside handler")
    print(exc_info)
   
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path, onerror = handler)


输出:

python shutil.rmtree()

示例 2:通过传递 ignore_errors = False。

Python3

# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path, ignore_errors = False)
   
# making ignore_errors = True will not raise 
# a FileNotFoundError

输出:

示例 3:通过传递 onerror。
在 onerror 中,应该传递一个必须包含三个参数的函数。

  • 函数:引发异常的函数。
  • 路径:传递的路径名,在删除时引发异常
  • excinfo: sys.exc_info() 引发的异常信息

下面是实现。

Python3

# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
   
# exception handler
def handler(func, path, exc_info):
    print("Inside handler")
    print(exc_info)
   
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path, onerror = handler)

输出: