Welcome, guest | Sign In | My Account | Store | Cart

If there is a particular directory that you want purged of its files and want a solution in Python, this simple program is designed to do just that. This recipe is just meant as a starting point for those wondering how to delete all files and sub-folders from a central folder.

Python, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import os, sys

def main(path=''):
    if len(sys.argv) == 1 and path:
        try:
            delete(path)
        except:
            print 'ERROR: Internal Path'
    else:
        try:
            delete(' '.join(sys.argv[1:]))
        except:
            print os.path.basename(sys.argv[0]), '<directory>'

def delete(path):
    for name in os.listdir(path):
        path_name = os.path.join(path, name)
        try:
            if os.path.isdir(path_name):
                delete(path_name)
                os.rmdir(path_name)
            elif os.path.isfile(path_name):
                os.remove(path_name)
        except:
            print 'ERROR:', path_name

if __name__ == '__main__':
    main(r'C:\Documents and Settings\SCHAP472')