[Tutor] removedirs ?
Jason Child
jasonchild at cnsp.com
Thu Dec 16 22:10:44 CET 2004
is this what you want to do?
import os
from os.path import join
# Delete everything reachable from the directory named in 'top'.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(join(root, name))
for name in dirs:
os.rmdir(join(root, name))
I cant take credit for the code, as I found it when I was trying to hack
together a recirsive file remover script. It was in the help files for
the os module, under walk(). Go figure; when you try to do things the
"hard way" python keeps it simple!
Peace
Jason
Ertl, John wrote:
>Jason,
>
>I could...That is the exact feature I am trying to replicate, but I would
>just like to do it in Python if I can (in a simple way). I am writing this
>code in Python to avoid some funny scripting that I would need to do. To go
>back to combing shell and Python again would be a bit deflating...but the
>straight forward path might be the best.
>
>Thanks,
>
>John Ertl
>
>
>-----Original Message-----
>From: Jason Child [mailto:jasonchild at cnsp.com]
>Sent: Thursday, December 16, 2004 12:36
>Cc: tutor at python.org
>Subject: Re: [Tutor] removedirs ?
>
>Ertl, John wrote:
>
>
>
>>I am trying to remove a directory that has other directories and files in
>>it. I thought removedirs was supposed to do a recursive remove of files
>>
>>
>and
>
>
>>directories.
>>
>>When I try it I get
>>
>>
>>
>>
>>
>>>>>os.removedirs("DAF")
>>>>>
>>>>>
>>>>>
>>>>>
>>Traceback (most recent call last):
>> File "<pyshell#11>", line 1, in -toplevel-
>> os.removedirs("DAF")
>> File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
>>removedirs
>> rmdir(name)
>>OSError: [Errno 17] File exists: 'DAF'
>>
>>Thanks,
>>
>>John Ertl
>>
>>
>>_______________________________________________
>>Tutor maillist - Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
>>
>>
>it seems to me that if its on a *nix box you could use the shell command
>rm -rf <target>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>
More information about the Tutor
mailing list