python实例31[文件夹清理]

 

使用:

foldercleanup.py -d 10 -k c:\test\keepfile.txt c:\test

表示对c:\test目录只保留最近10天的子文件夹和keepfile.txt中指定的子文件夹。

 

代码:  


import os
import os.path
import datetime
  
def getOption():
  
from optparse import OptionParser
  
  des   
= "clean up the folder with some options"
  prog  
= "foldercleanup"
  ver   
= "%prog 0.0.1"
  usage 
= "%prog [options] foldername"
  
  p 
= OptionParser(description=des, prog=prog, version=ver, usage=usage,add_help_option=True)
  p.add_option(
'-d','--days',action='store',type='string',dest='days',help="keep the subfolders which are created in recent %days% days")
  p.add_option(
'-k','--keepfile',action='store',type='string',dest='keepfile',help="keep the subfolders which are recorded in text file %keepfile% ")
  options, arguments 
= p.parse_args()
  
  
if len(arguments) != 1:
    
print("error: must input one directory as only one parameter ")
    
return
  
  
return options.days, options.keepfile, arguments[0]  

 
def preCheckDir(dir):
  
if(not os.path.exists(dir)):
    
print("error: the directory your input is not existed")
    
return
  
if(not os.path.isdir(dir)):
    
print ("error: the parameter your input is not a directory")
    
return
    
  
return os.path.abspath(dir)
  
def isKeepByDay(dir, day):
  indays 
= False
  
if( day is not None) :
    t 
= os.path.getctime(dir)
    today 
= datetime.date.today()
    createdate 
= datetime.date.fromtimestamp(t)
    indate 
= today - datetime.timedelta(days = int(day))
    
print (createdate)
    
if(createdate >= indate):
      indays 
= True
  
print (indays)
  
return indays
  
def isKeepByKeepfile(dir, keepfile):
  needkeep 
= False
  
print (dir)
  
if (keepfile is not None):
    
try :
      kf 
= open(keepfile,"r")
      
for f in kf.readlines():
        
print (f)
        
if (dir.upper().endswith("\\" + f.strip().upper())):
          needkeep 
= True
      kf.close()
    
except:
      
print ("error: keep file cannot be opened")
  
print(needkeep)
  
return needkeep
    
def removeSubFolders(dir, day, keepfile):
  subdirs 
= os.listdir(dir)
  
for subdir in subdirs:
    subdir 
= os.path.join(dir,subdir)
    
if ( not os.path.isdir(subdir)):
      
continue
    
print("----------------------")
    
if( (not isKeepByDay(subdir, day))and (not isKeepByKeepfile(subdir, keepfile))):
      
print("remove subfolder: " + subdir)
      
import shutil
      shutil.rmtree(subdir,True)
    
def FolderCleanUp():
  (day, keepfile, dir) 
= getOption()
  dir 
= preCheckDir(dir)
  
if dir is None:
    
return
  removeSubFolders(dir,day,keepfile)
  
if __name__=='__main__':
  FolderCleanUp()

 

对目录下保留最后的zip文件:

def KeepLastNumZips(num)
    
def extractTime(f):
        
return os.path.getctime(f)

    zipfiles 
= [os.path.join(zipdir, f)
                
for f in os.listdir(zipdir)
                
if os.path.splitext(f)[1== ".zip"]
    
if len(zipfiles) > num:
        zipfiles.sort(key
=extractTime, reverse=True)
        
for i in range(num, len(zipfiles)):
            os.remove(zipfiles[i])

 

 

 

完!

转载于:https://www.cnblogs.com/itech/archive/2011/01/11/1915718.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/462801.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MySQL中的alter table操作之add/modify/drop列

alter table的操作有增加列、删除列和修改列的长度等 create table t1 (c1 int primary key) engine innodb; // 增加一个列c2 alter table t1 add c2 varchar(16379); drop table t1;create table t1 (c1 int primary key, c2 varchar(50)) engine innodb; // 将列c2长度更…

SUSE Linux启动过程执行脚本顺序

网上看到的,备忘 mbr->grub->menu.lst->vmlinuz(linux)->initrd->etc/inittab->/etc/rc.status->/etc/sysconfig/boot->/etc/init.d/boot.d/*->/etc/init.d/boot.local->/etc/rc.d/rc*.d/*->mingetty->login->/etc/profile.…

jdk8 Function

例子 1&#xff1a; // 定义function Function<String, String> fun parm -> { // 这里是定function中的逻辑 return String.valueOf(parm "xing"); };Function<String, String> fun1 parm -> { // 这里是定function中的逻辑 return String.val…

std::unique_ptr<T>与boost::scoped_ptr<T>的特殊性

std::unique_ptr<T>与boost::scoped_ptr<T>的底层实现原理类型&#xff0c;不清楚是谁"借鉴"另一个的实现的&#xff0c;但这不重要。 std::unique_ptr<T>与boost::scoped_ptr<T> 都禁用了拷贝构造和赋值函数&#xff0c;所以不能作为STL容…

winform Outlookbar

控件提供了一种类似Outlook方式的工具条&#xff0c;用来切换各种业务窗口&#xff0c;用上这个控件&#xff0c;肯定为您的程序增色不少。这个控件结合上面介绍的布局控件"WeifenLuo.WinFormsUI.Docking"&#xff08;具体见文章WinForm界面开发之布局控件"Weif…

[leetcode](4.21)4. 有效子数组的数目

给定一个整数数组 A&#xff0c;返回满足下面条件的 非空、连续 子数组的数目&#xff1a; 子数组中&#xff0c;最左侧的元素不大于其他元素。 示例 1&#xff1a; 输入&#xff1a;[1,4,2,5,3] 输出&#xff1a;11 解释&#xff1a;有 11 个有效子数组&#xff0c;分别是&…

Android SDK 2.2 开发环境安装

本文描述 Android SDK 安装过程&#xff0c;包括&#xff1a;Android SDK 2.2, Eclipse 3.5.2(galileo), 和 Andoid Development Tools (ADT) Plugin。一个前提是用户已经安装了 JDK5.0 或 jdk 6.0。并且在系统环境变量设置了 Path 包含 JDK 的 bin 目录。编辑本段 回目录安装 …

std::make_shared<T>/std::make_unique<T>与std::shared_ptr<T>/std::unique_ptr<T>的区别与联系

(1)、std::make_shared<T>与std::make_unique<T>相对于std::shared_ptr<T>/std::unique_ptr<T>只有一次内存的分配 (2)、std::make_shared<T>与std::make_unique<T>不会抛出异常&#xff1b; 此外&#xff0c;std::make_shared<T>是…

Hibernate实体JSONObject化时遇到的问题

2019独角兽企业重金招聘Python工程师标准>>> ###在对Hibernate持久化的对象进行JSON化的时候&#xff0c;出现了几个问题。 第一个是因为在对象中有相互引用&#xff0c;如A->B,B.set->A这样的一对多关系&#xff0c;使得在遍历构造JSON时&#xff0c;产生了死…

截取中英文字符串

代码 functionsubstr(str, len){if(!str ||!len) { return; }//预期计数&#xff1a;中文2字节&#xff0c;英文1字节vara 0;//循环计数vari 0;//临时字串vartemp ;for(i0;i<str.length;i){if(str.charCodeAt(i)>255){//按照预期计数增加2a2; }else{ a; }//如果增加计数…

mysql概述

MySql大致分为三层结构&#xff1a; 第一层&#xff1a;客户端并非MySql所独有&#xff0c;例如&#xff1a;连接处理、授权认证、安全等功能均在这一层处理 第二层&#xff1a;核心服务包括查询解析、分析、优化、缓存、内置函数(比如 : 时间、数学、加密等函数)&#xff0c;所…

mysql 8.0 一条insert语句的具体执行流程分析(二)

继续上一篇文章&#xff1a;mysql 8.0 一条insert语句的具体执行流程分析(一)_一缕阳光的博客-CSDN博客 由于最近换工作一直在试用期内&#xff0c;在拼命的学习、总结中&#xff0c;因此没有时间写文章&#xff0c;今天转正了腾出来时间继续写下一篇文章。mysql 8.0 一条inse…

关于C#序列化结果的长度获取

关于C#序列化的文章真的是好多&#xff0c;但是内容大致一样&#xff0c;主要分四类&#xff1a; BinarySerialize SoapSerialize XmlSerialize JSON.Net和DataContractJsonSerializer最近的一个项目需要使用Socket进行通信&#xff0c;所以必然涉及序列化的问题。使用BinarySe…

团队项目-需求分析

团队作业-需求分析 这个作业属于哪个课程https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2这个作业的要求在哪里https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2/homework/3105团队名称快乐小分队这个作业的目标完成英语学习app&#xff0c;尽量…

REMarkerClusterer

2019独角兽企业重金招聘Python工程师标准>>> REMarkerClusterer 创建和管理大量的标记每个缩放级别的集群。REMarkerClusterer 受苹果的照片应用程序在iPhone上的启发&#xff0c;模仿它的行为提供分组和取消分组集群的动画。 转载:http://www.adobex.com/ios/sourc…

mysql 8.0 一条insert语句的具体执行流程分析(三)

代码版本&#xff1a;mysql 8.0.22 编程语言&#xff1a;c && c11 && c14 && c17 上一篇文章&#xff1a;mysql 8.0 一条insert语句的具体执行流程分析(二)_一缕阳光的博客-CSDN博客 主要介绍了存储引擎部分&#xff0c;这个章节主要介绍insert一条…

corosync+openais+pacemaker+web

corosync 和openais 各自都能实现群集功能&#xff0c;但是功能比较简单&#xff0c;要想实现功能齐全、复杂的群集&#xff0c;需要将两者结合起来.corosync 和openais 各自都能实现群集功能&#xff0c;但是功能比较简单&#xff0c;要想实现功能齐全、复杂的群集&#xff0c…

Asp.net MVC 3实例学习之ExtShop(五)——产品详细页

在产品详细页需要使用到tab控件&#xff0c;在jquery的ui包已包含改控件&#xff0c;因而将相应文件链接加到母版页就可以了。 打开“ProductController”文件&#xff0c;在里面添加一个Details操作&#xff0c;代码如下&#xff1a; 1 public ActionResu…

解构领域驱动设计(三):领域驱动设计

在上一部分&#xff0c;分层架构的目的是为了将业务规则剥离出来在单独的领域层中进行实现。再回顾一下领域驱动设计的分层中应用层代码的实现。 Override public void pay(int orderId, float amount) {DesignerOrder order designerOrderRepository.selectByKey(orderId); …

MySQL中update一条record的过程

在MySQL中&#xff0c;update是原地更新数据&#xff0c;原地更新数据&#xff0c;原地更新数据。重要的事情说3遍。这是不同于PGSQL的。 update的具体过程是&#xff1a; (1)、先对该条record对应的索引加X锁 (2)、将修改后的数据写入到redo.log中 (3)、将修改之前的数据备…