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

yipeiwu_com6年前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统计文件行数示例分享

复制代码 代码如下:import time def block(file,size=65536):    while True:  &n...

python处理中文编码和判断编码示例

下面所说的都是针对python2.7 复制代码 代码如下:#coding:utf-8#chardet 需要下载安装 import chardet#抓取网页htmlline = "http...

Python 数据结构之堆栈实例代码

Python 堆栈 堆栈是一个后进先出(LIFO)的数据结构. 堆栈这个数据结构可以用于处理大部分具有后进先出的特性的程序流 . 在堆栈中, push 和 pop 是常用术语:...

关于Flask项目无法使用公网IP访问的解决方式

关于Flask项目无法使用公网IP访问的解决方式

最近在折腾Python Web,在测试的时候发现,本机可以正常访问,但外网无法通过公网IP访问页面。经过各种搜索,有大致三种解决方案。 一、修改/添加安全组端口 这是第一种方案,也是能解...

python发送多人邮件没有展示收件人问题的解决方法

背景: 工作过程中需要对现有的机器、服务做监控,当服务出现问题后,邮件通知对应的人 问题: 使用python 2.7自带的email库来进行邮件的发送,但是发送后没有展示收件人列表内容...