问题描述
我正在使用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)
查看运行代码后将删除哪些文件