Python标准库shutil中rmtree()使用回调函数

这段代码目的是删除包含只读文件的文件夹,主要演示回调函数的用法。

>>> import os

>>> import stat

>>> import shutil

>>> def remove_readonly(func, path, _): #定义回调函数

os.chmod(path, stat.S_IWRITE)     #删除文件的只读属性

func(path)                                       #再次执行删除操作

>>> shutil.rmtree('D:\\des_test') #文件夹中有个只读文件,删除失败

Traceback (most recent call last):

  File "<pyshell#21>", line 1, in <module>

    shutil.rmtree('D:\\des_test')

  File "C:\Python35\lib\shutil.py", line 488, in rmtree

    return _rmtree_unsafe(path, onerror)

  File "C:\Python35\lib\shutil.py", line 383, in _rmtree_unsafe

    onerror(os.unlink, fullname, sys.exc_info())

  File "C:\Python35\lib\shutil.py", line 381, in _rmtree_unsafe

    os.unlink(fullname)

PermissionError: [WinError 5] 拒绝访问。: 'D:\\des_test\\test1.txt'

>>> shutil.rmtree('D:\\des_test', οnerrοr=remove_readonly) #指定回调函数,删除成功

转自:Python标准库shutil中rmtree()使用回调函数

Python中,`shutil`模块提供了许多高级的文件操作功能,其中`rmtree`函数用于删除一个目录及其所有内容。以下是`shutil.rmtree`的基本用法和注意事项: ### 基本用法 ```python import shutil # 指定要删除的目录路径 directory_path = '/path/to/directory' # 删除目录及其所有内容 shutil.rmtree(directory_path) ``` ### 注意事项 1. **不可恢复**:使用`shutil.rmtree`删除的目录和文件是不可恢复的,因此在执行此操作时要非常小心,确保路径正确。 2. **权限问题**:确保运行脚本的用户具有删除目标目录及其内容的权限,否则会引发权限错误。 3. **异常处理**:为了提高脚本的健壮性,建议使用异常处理来捕获可能发生的错误。 ### 带异常处理的示例 ```python import shutil import os directory_path = '/path/to/directory' try: shutil.rmtree(directory_path) print(f"目录 {directory_path} 及其所有内容已成功删除。") except FileNotFoundError: print(f"错误:目录 {directory_path} 不存在。") except PermissionError: print(f"错误:没有权限删除目录 {directory_path}。") except Exception as e: print(f"发生错误:{e}") ``` ### 参数说明 - `path`:要删除的目录的路径。 - `ignore_errors=False`:如果设置为`True`,则忽略错误。 - `onerror`:一个可选的回调函数,用于处理`os.listdir()`和`os.remove()`等函数引发的错误。 通过上述内容,你可以使用`shutil.rmtree`来删除指定的目录及其所有内容,但在使用时要格外小心,以免误删重要数据。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值