SoFunction
Updated on 2024-10-30

Python 2.7 Delete Folder and Delete File Code Examples


#!c:\python27\
# -*- coding: utf-8 -*-

import os
import re

from os import path
from shutil import rmtree

DEL_DIRS = None
DEL_FILES = r'(.+?\.pyc$|.+?\.pyo$|.+?\.log$)'

def del_dir(p):
    """Delete a directory."""
    if (p):
        rmtree(p)
        print('D : %s' % p)

def del_file(p):
    """Delete a file."""
    if (p):
        (p)
        print('F : %s' % p)

def gen_deletions(directory, del_dirs=DEL_DIRS, del_files=DEL_FILES):
    """Generate deletions."""
    patt_dirs = None if del_dirs == None else (del_dirs)
    patt_files = None if del_files == None else (del_files)

    for root, dirs, files in (directory):
        if patt_dirs:
            for d in dirs:
                if patt_dirs.match(d):
                    yield (root, d)
        if patt_files:
            for f in files:
                 if patt_files.match(f):
                    yield (root, f)

def confirm_deletions(directory):
    import Tkinter
    import tkMessageBox

    root = ()
    ()
    res = ("Confirm deletions?",
        "Do you really wish to delete?\n\n"
        "Working directory:\n%s\n\n"
        "Delete conditions:\n(D)%s\n(F)%s"
        % (directory, DEL_DIRS, DEL_FILES))
    if res:
        print('Processing...')
        m, n = 0, 0
        for p in gen_deletions(directory):
            if (p):
                del_dir(p)
                m += 1
            elif (p):
                del_file(p)
                n += 1
        print('Clean %d dirs and %d files.' % (m, n))
        ()
    else:
        print('Canceled.')
        ()

    ()

if __name__ == '__main__':
    import sys
    argv =
    directory = argv[1] if len(argv) >= 2 else ()
    confirm_deletions(directory)
    # import subprocess
    # ("pause", shell=True)