Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Empty A Directory

Status
Not open for further replies.

turncom

Programmer
May 3, 2002
19
0
0
US
Okay, I am new to Python. I really like it, by the way.

I need to be pointed in the right direction. I need to empty a directory. There will be files, and sub-directories that also need to be emptied.

I took a look at os.rmdir('c:/foo') but if there are files in it, you get an error message.

So obviously, you have to remove() files, one by one. When I use os.listdir('c:/foo'), it lists everything - files and directories. You could use this to get a list of the files, but you would have directories in there, too. So you have to put in some isdir() or isfile() in there.

I bet there is an efficient way to do this. I am sure someone has witten code for this before. Do you have it? Is it in a book? Is it in the documentation, and I have missed it? I really think it is silly to re-invent the wheel.

Thanks for your help.
 
Let me reply to my own post. I kept digging around and found the following:
shutil.rmtree(path[, ignore_errors [, onerror]])

Seems to do the trick. Removes everything, including the directory.

I *knew* there had to be an efficient easy way to do this.
:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top