2

This is part of a program I'm writing. The goal is to extract all the GPX files, say at G:\ (specified with -e G:\ at the command line). It would create an 'Exports' folder and dump all files with matching extensions there, recursively that is. Works great, a friend helped me write it!! Problem: empty directories and subdirectories for dirs that did not contain GPX files.

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)

Later in the program we have the call for extractpath():

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

So the above extraction does work. But the len function call above is designed to prevent the creation of empty dirs and does not. I know the best way is to os.rmdir somehow after the export, and while there's no error, the folders remain.

So how can I successfully prune this Exports folder so that only dirs with GPXs will be in there? :)

kaya3
  • 47,440
  • 4
  • 68
  • 97
Interrupt
  • 965
  • 3
  • 9
  • 16

1 Answers1

1

If I understand you correctly, you want to delete empty folders? If that is the case, you can do a bottom up delete folder operation -- which will fail for any any folders that are not empty. Something like:

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
user590028
  • 11,364
  • 3
  • 40
  • 57
  • I got this code to work but not fully. Using your code's concept as a model, I was able to get rid of most of the directories. There is 3 more. 2 empties, one with many empty subdirs still. Why? Weird right? Here is what it looks like now: codepad.org/CiLjjR7u -- New Edit: one more ``os.rmdir(root)`` after ``os.rmdir(pth)`` gets another folder, still not 100%. So strange. – Interrupt Aug 11 '13 at 20:53