简体   繁体   中英

Recursively delete folders

I wrote this Python script a while ago to recursively delete all folders and sub-folders if they end in the sub-string "DEF.html".

It on the first directory within which it is called, but any recursive calls fail.

Any idea why? I'm sure I had it running before.

import os
def deleteFiles(path):
 files = os.listdir(path)
 for f in files:
  if not os.path.isdir(f) and "def.html" in f:
   os.remove(f)
  if os.path.isdir(f):
   deleteFiles(os.path.join(path, f))

deleteFiles(os.path.join('C:\\', 'Users', 'ADMIN', 'Desktop', 'Folder', 'Test'))

Folder structure is :

>Test
 >Folder1
   abc.html
   def.html
  >subfolder
   def.html #notDeleted
   abc1.html
 >Folder2
 ....

There can be up to n subfolders and Test contains Folders 1-n also. It executes with no error and logically I can see nothing wrong.

Any ideas?

When you call os.path.isdir(f) , you're checking for the existence of f in the current working directory, rather than the path directory. Try using os.path.join on f before using it in your conditionals.

import os
def deleteFiles(path):
 files = os.listdir(path)
 print files
 for f in files:
  f = os.path.join(path, f)
  if not os.path.isdir(f) and "def.html" in f:
   os.remove(f)
  if os.path.isdir(f):
   deleteFiles(f)

deleteFiles('Test')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM