如何解决尝试删除包含某些字符的目录
我正在使用python删除任何名称包含硬括号(以及该目录中的所有内容)的目录。 (例如[dirname],[dirname2] ...)
import os
import glob
import shutil # delete an entire dir tree
# get a recursive list of file paths that matches pattern including sub directories
fileList = glob.glob('C:/Users/stef/Desktop/python test folder/[*]',recursive=True)
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
try:
shutil.rmtree(filePath)
except OSError:
print("Error while deleting file")
抛出有关“递归”的错误。我正在使用Python 3.8.5。 TypeError:glob()得到了意外的关键字参数“递归”
在执行此脚本之前,我还需要帮助弄清楚空运行情况。
谢谢!
解决方法
您可以使用pathlib模块中的pathlib.Path.rglob。
from pathlib import Path
fileList = Path('C:/Users/stef/Desktop/python test folder').rglob('[*]')
for filePath in fileList:
try:
shutil.rmtree(filePath)
except OSError:
print("Error while deleting file")
对于干燥运行,我建议更改生产线
shutil.rmtree(filePath)
至
print(filePath)
查看运行代码后将删除哪些文件
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。