views:

42

answers:

3

When coding in Python, I often need to write a function like this one:

def delete_dir(dir_name):

    if os.path.exists(dir_name):
        reply = raw_input("Delete directory "+dir_name+"? [y/[n]] ")
        if reply=='y':
            os.system('rm -r '+dir_name)
        else:
            print "Aborting..."
            sys.exit()

which is basically just a remove command with a user prompt to double-check (I also have one for deleting files). Given the large amounts of Python modules out there, including in the standard library, I'm wondering if something like this already exists out there?

A: 

to remove directory, use os module os.rmdir(), os.removedirs(). Or shutil.rmtree() .check the docs for more information

ghostdog74
I agree these can replace the os.system('rm -r '+dir_name) line, but what I'm looking for is a routine that will automatically give a user prompt to double check if the directory should be deleted.
astrofrog
A: 

well ,you could save this function in a module and reuse it in other modules,that way ,your problem will be solved !

appusajeev
+2  A: 

It wouldn't be a Python thing, but if you keep using os.system() to make the delete call, you can pass the -i parameter to rm. The man page explains it:

-i       prompt before every removal

EDIT: I just read your code again and it looks like you're only prompting once before the entire delete process, not for each file. You might be interested in the -I flag instead:

-I       prompt once before removing more than three files, or when removing recursively. Less intrusive than -i, while still giving protection against most mistakes

Roman Stolper