views:

90

answers:

3

I have the following Python code to remove files in a directory. For some reason my .svn directories are not being recognised as directories.

And I get the following output:

.svn not a dir

Any ideas would be appreciated.

def rmfiles(path, pattern):
    pattern = re.compile(pattern)
    for each in os.listdir(path):
        if os.path.isdir(each) != True:
            print(each +  " not a dir")
            if pattern.search(each):
                name = os.path.join(path, each)
                os.remove(name)
+4  A: 

You need to create the full path name before checking:

if not os.path.isdir(os.path.join(path, each)):
  ...
unwind
Thanks so much!!
Dan
+1  A: 

You will need to os.path.join the path you invoke listdir on with the found file/directory, i.e.

for each in os.listdir(path):
    if os.path.isdir(os.path.join(path, each)):
        ....

If you don't create an absolute path this way you will be testing against your current working directory in stead, which probably dioesn't have the svn directory.

Also, don't explicitly compare boolean values. Let if handle it as a boolean expression (some functions may return non True/False truth values, i.e. None or an instance)

Ivo van der Wijk
A: 

You could also switch to the target directory instead of constructing an absolute path.

def rmfiles(path, pattern):
    pattern = re.compile(pattern)
    oldpath = os.getcwd()     # <--
    os.chdir(path)            # <--
    try:
      for each in os.listdir('.'):
        if os.path.isdir(each) != True:
            print(each +  " not a dir")
            if pattern.search(each):
                name = os.path.join(path, each)
                os.remove(name)
    finally:
      os.chdir(oldpath)       # <--
KennyTM