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

yipeiwu_com4年前Python基础

复制代码 代码如下:

#!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\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)

相关文章

python中将字典转换成其json字符串

#这是Python中的一个字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': {...

python使用HTMLTestRunner导出饼图分析报告的方法

python使用HTMLTestRunner导出饼图分析报告的方法

目录如下: 这里有使用 HTMLTestRunner和 echarts.common.min.js文件[见百度网盘,这里给自己留个记录便于查询] unit_test.py代码如下:...

Python简单网络编程示例【客户端与服务端】

本文实例讲述了Python简单网络编程。分享给大家供大家参考,具体如下: 内容目录 1. 客户端(client.py) 2. 服务端(server.py) 一、客户端(client.py...

python中判断文件编码的chardet(实例讲解)

1、实测,这个版本在32位window7和python3.2环境下正常使用。  2、使用方法:把解压后所得的chardet和docs两个文件夹拷贝到python3.2目录下的L...

Python3实现的简单工资管理系统示例

本文实例讲述了Python3实现的简单工资管理系统。分享给大家供大家参考,具体如下: 工资管理系统要求: 1. 查询员工工资 2. 修改员工工资 3. 增加新员工记录 4. 退出 执行代...