21

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)
Sam
  • 7,252
  • 16
  • 46
  • 65
Dan
  • 9,681
  • 14
  • 55
  • 70

3 Answers3

61

You need to create the full path name before checking:

if not os.path.isdir(os.path.join(path, each)):
  ...
unwind
  • 391,730
  • 64
  • 469
  • 606
3

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
  • 16,341
  • 4
  • 43
  • 57
  • There's a method called abspath in ospath, and yet this isn't working for me either. Do you know why this wouldn't work? – vargonian Feb 14 '14 at 21:11
0

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
  • 510,854
  • 105
  • 1,084
  • 1,005