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

This program was used to search for files with certain extentions and then to delete them while carefully reporting all errors. The recipe does not accept command-line arguments but works well.

Python, 41 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
29
30
31
32
33
34
35
36
37
38
39
40
41
import os

def main():
    try:
        while True:
            while True:
                mode = raw_input('Mode: ').lower()
                if 'search'.startswith(mode):
                    mode = False
                    break
                elif 'destroy'.startswith(mode):
                    mode = True
                    break
                print '"search" or "destroy"'
            path = raw_input('Path: ')
            extention = raw_input('Extention: ')
            for path_name in search(path, extention, mode):
                print 'Found:', path_name
    except:
        pass

def search(path, extention, destroy):
    assert os.path.isdir(path)
    path_list = list()
    for name in os.listdir(path):
        path_name = os.path.join(path, name)
        try:
            if os.path.isdir(path_name):
                path_list += search(path_name, extention, destroy)
            elif os.path.isfile(path_name):
                if path_name.endswith(extention) or not extention:
                    if destroy:
                        os.remove(path_name)
                    else:
                        path_list.append(path_name)
        except:
            print 'Error:', path_name
    return path_list

if __name__ == '__main__':
    main()

Before creating an archive of your information, it may be helpful to delete all files with a certain extention. Some examples include db, ini, pyc, bak, Before creating an archive of your information, it may be helpful to delete all files with a certain extention. Some examples include db, ini, pyc, bak,

1 comment

Alia Khouri 15 years, 2 months ago  # | flag

You may want to check out Recipe 576643 for a similar (but inmho more extensible) script with command line options.