python2.7 Delete folders and delete file code instances _python

Source: Internet
Author: User
Tags join

Copy Code code 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 Directory A." ""
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 = N one 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 your 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 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 (' Canceled. ')
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.