recursively removing files and directories

R

rbt

What is the most efficient way to recursively remove files and directories?

Currently, I'm using os.walk() to unlink any files present, then I call
os.walk() again with the topdown=False option and get rid of diretories
with rmdir. This works well, but it seems that there should be a more
efficient way. Here are my function definitions:

def remove_files(target_dir):
# This attempts to remove _all_ files from a directory.
# Use with caution on directories that store temporary files.

for root, dirs, files in os.walk(target_dir):
for f in files:

try:
# Make attributes normal so file can be deleted.
win32api.SetFileAttributes(os.path.join(root, f),
win32con.FILE_ATTRIBUTE_NORMAL)
except:
pass

try:
# Try to delete the file.
os.unlink(os.path.join(root, f))
except:
pass

def remove_dirs(target_dir):
# This attempts to remove _all_ sub directories from a directory.
# Use with caution on directories that store temporary information.

for root, dirs, files in os.walk(target_dir, topdown=False):
for d in dirs:

try:
# Make attributes normal so dir can be deleted.
win32api.SetFileAttributes(os.path.join(root, d),
win32con.FILE_ATTRIBUTE_NORMAL)
except:
pass

try:
# Try to delete the directory.
os.rmdir(os.path.join(root, d))
except:
pass
 
T

Tim N. van der Leeuw

Wasn't this the example given in the Python manuals? Recursively
deleting files and directories?

cheers,

--Tim
 
R

rbt

Tim said:
Wasn't this the example given in the Python manuals? Recursively
deleting files and directories?

I don't know... I wrote it without consulting anything. Hope I'm not
infringing on a patent :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top