Python: delete folder t and delete File Code instances. For more information, see. the runtime environment is python2.7.
The code is as follows:
#! C: \ python27 \ python.exe
#-*-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 path. isdir (p ):
Rmtree (p)
Print ('d: % s' % p)
Def del_file (p ):
"Delete a file ."""
If path. isfile (p ):
OS. remove (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 re. compile (del_dirs)
Patt_files = None if del_files = None else re. compile (del_files)
For root, dirs, files in OS. walk (directory ):
If patt_dirs:
For d in dirs:
If patt_dirs.match (d ):
Yield path. join (root, d)
If patt_files:
For f in files:
If patt_files.match (f ):
Yield path. join (root, f)
Def confirm_deletions (directory ):
Import Tkinter
Import tkMessageBox
Root = Tkinter. Tk ()
Root. withdraw ()
Res = tkMessageBox. askokcancel ("Confirm deletions? ",
"Do you really wish to delete? \ N"
"Working directory: \ n % s \ 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 path. isdir (p ):
Del_dir (p)
M + = 1
Elif path. isfile (p ):
Del_file (p)
N + = 1
Print ('Clean % d dirs and % d files. '% (m, n ))
Root. destroy ()
Else:
Print ('celed .')
Root. destroy ()
Root. mainloop ()
If _ name _ = '_ main __':
Import sys
Argv = sys. argv
Directory = argv [1] if len (argv)> = 2 else OS. getcwd ()
Confirm_deletions (directory)
# Import subprocess
# Subprocess. call ("pause", shell = True)