【问题标题】:Python - empty dirs & subdirs after a shutil.copytree functionPython - shutil.copytree 函数后的空目录和子目录
【发布时间】:2013-08-10 18:55:42
【问题描述】:

这是我正在编写的程序的一部分。目标是提取所有 GPX 文件,例如在 G:\(在命令行中使用 -e G:\ 指定)。它将创建一个“Exports”文件夹并在那里递归地转储所有具有匹配扩展名的文件。很好用,朋友帮我写的!!问题:不包含 GPX 文件的目录的空目录和子目录。

import argparse, shutil, os

def ignore_list(path, files): # This ignore list is specified in the function below.
    ret = []
    for fname in files:
         fullFileName = os.path.normpath(path) + os.sep + fname
         if not os.path.isdir(fullFileName) \
            and not fname.endswith('gpx'):
            ret.append(fname)
         elif os.path.isdir(fullFileName) \ # This isn't doing what it's supposed to.
            and len(os.listdir(fullFileName)) == 0:
            ret.append(fname)
    return ret

def gpxextract(src,dest):    
    shutil.copytree(src,dest,ignore=ignore_list)

在程序的后面,我们调用了extractpath()

if args.extractpath:
    path = args.extractpath
    gpxextract(extractpath, 'Exports')

所以上面的提取确实有效。但是上面的len 函数调用旨在防止创建空目录并且没有。我知道最好的方法是os.rmdir 以某种方式 导出之后,虽然有no 错误,但文件夹仍然存在。

那么我怎样才能成功地修剪这个 Exports 文件夹,以便只有带有 GPX 的目录才会在那里? :)

【问题讨论】:

    标签: python extract pruning


    【解决方案1】:

    如果我理解正确,您想删除空文件夹吗?如果是这种情况,您可以执行自下而上的删除文件夹操作——这对于任何非空文件夹都将失败。比如:

    for root, dirs, files in os.walk('G:/', topdown=true):
        for dn in dirs:
            pth = os.path.join(root, dn)
            try:
                os.rmdir(pth)
            except OSError:
                pass
    

    【讨论】:

    • 我得到了这段代码,但没有完全工作。使用您的代码概念作为模型,我能够摆脱大多数目录。还有3个。 2 个空,一个还有许多空子目录。为什么?很奇怪吧?这是现在的样子:codepad.org/CiLjjR7u - 新编辑:os.rmdir(root)os.rmdir(pth) 获得另一个文件夹之后,仍然不是 100%。好奇怪。
    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多