python2.7删除文件夹和删除文件代码实例

代码如下:

#!c:\python27\python.exe# -*- coding: utf-8 -*-

import osimport re

from os import pathfrom shutil import rmtree

del_dirs = nonedel_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\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)