def remove_dir_if_empty(path, ignore_metadata_caches=False):
 try:
  os.rmdir(path)
 except OSError as e:
  if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)):
   if ignore_metadata_caches:
    try:
     found = False
     for x in os.listdir(path):
      if (x.lower() in {'.ds_store', 'thumbs.db'}):
       found = True
       x = os.path.join(path, x)
       if os.path.isdir(x):
        import shutil
        shutil.rmtree(x)
       else:
        os.remove(x)
    except Exception:
     found = False
    if found:
     remove_dir_if_empty(path)
   return
  raise

def remove_dir_if_empty ( path , ignore_metadata_caches = False ) : try : os . rmdir ( path ) except OSError as e : if ( ( e . errno == errno . ENOTEMPTY ) or ( len ( os . listdir ( path ) ) > 0 ) ) : if ignore_metadata_caches : try : found = False for x in os . listdir ( path ) : if ( x . lower ( ) in { '.ds_store' , 'thumbs.db' } ) : found = True x = os . path . join ( path , x ) if os . path . isdir ( x ) : import shutil shutil . rmtree ( x ) else : os . remove ( x ) except Exception : found = False if found : remove_dir_if_empty ( path ) return raise
remove a directory if it is empty or contains only the folder metadata caches from different oses .