Python2.7 delete folders and file code instances

Source: Internet
Author: User
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.