Python-空目录&;shutil.copytree函数后的子目录

Python-空目录&;shutil.copytree函数后的子目录,python,extract,pruning,ignorelist,Python,Extract,Pruning,Ignorelist,这是我正在写的程序的一部分。目标是提取所有GPX文件,比如G:\(在命令行中用-eg:\指定)。它将创建一个“Exports”文件夹,并将所有具有匹配扩展名的文件以递归方式转储到该文件夹中。作品很棒,一个朋友帮我写的!!问题:不包含GPX文件的目录和子目录为空 import argparse, shutil, os def ignore_list(path, files): # This ignore list is specified in the function below. r

这是我正在写的程序的一部分。目标是提取所有GPX文件,比如G:\(在命令行中用-eg:\指定)。它将创建一个“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()

因此,上述提取确实有效。但是上面的
len
函数调用旨在防止创建空dir,而不是。我知道最好的方法是导出后以某种方式
os.rmdir
,虽然没有错误,但文件夹仍然保留


那么,我如何才能成功地修剪这个导出文件夹,以便只有带有GPXs的dir才会在其中呢?:)

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

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(pth)
获取另一个文件夹后,再添加一个
os.rmdir(root)
,仍然不是100%。真奇怪。
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