【问题标题】:Trying to delete a directory containing certain characters试图删除包含某些字符的目录
【发布时间】:2020-11-30 14:36:05
【问题描述】:

使用 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() 得到了一个意外的关键字参数'recursive'

在执行此脚本之前,我还需要帮助弄清楚试运行。

提前致谢!

【问题讨论】:

    标签: python directory glob shutil


    【解决方案1】:

    您可以使用 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) 查看代码运行后哪些文件会被删除

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 2017-05-06
      • 2019-09-14
      • 1970-01-01
      • 2018-08-08
      • 2020-03-19
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多