python2.7删除文件夹和删除文件代码实例
时间:2023-06-02 14:41:17
#!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)
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python调试模式无响应解决案例
![](https://img.aspxhome.com/file/2023/0/101280_0s.jpg)
Python实现将MongoDB中的数据导入到MySQL
oracle 存储过程和触发器复制数据
一个月入门Python爬虫学习,轻松爬取大规模数据
![](https://img.aspxhome.com/file/2023/8/101148_0s.jpg)
Golang import 导入包语法及一些特殊用法详解
如何查看access数据库中各元素的最大容量
python占位符输入方式实例
浅谈keras使用中val_acc和acc值不同步的思考
![](https://img.aspxhome.com/file/2023/8/124208_0s.jpg)
Django2.1.7 查询数据返回json格式的实现
![](https://img.aspxhome.com/file/2023/9/63239_0s.png)
python技能之数据导出excel的实例代码
![](https://img.aspxhome.com/file/2023/5/124745_0s.png)
使用pandas中的DataFrame数据绘制柱状图的方法
![](https://img.aspxhome.com/file/2023/1/105721_0s.jpg)
使用Python读取二进制文件的实例讲解
![](https://img.aspxhome.com/file/2023/9/72969_0s.jpg)
python Pexpect模块的使用
在python中实现导入一个需要传参的模块
![](https://img.aspxhome.com/file/2023/4/111994_0s.png)
JavaScript实现烟花特效(面向对象)
TensorFlow的环境配置与安装方法
![](https://img.aspxhome.com/file/2023/6/113166_0s.png)
python批量从es取数据的方法(文档数超过10000)
用javascript控制iframe滚动的代码
Python urllib库如何添加headers过程解析
JSP自定义标签Taglib实现过程重点总结
![](https://img.aspxhome.com/file/2023/5/97905_0s.png)