返回顶部

收藏

复制文件到指定目录(根据最近时间(天数和秒数))

更多
# coding=utf-8
#py2.7
# 功能:根据天数和秒数复制文件到指定目录,保留文件创建时间和修改时间
import datetime
import os
import shutil
from stat import ST_CTIME, ST_MTIME
import types

# 不支持递归子目录
table={
    r'源文件夹':r'目标文件夹'
}
# 创建多级空目录
def mkdirs(dirs):
    if not type(dirs) is types.StringType:
        for dir in dirs:
            if not os.path.isdir(dir):
                print dir+"\t"*5+"created!"
                os.makedirs(dir)
    else:
        if not os.path.isdir(dirs):
            print dirs+"\t"*5+"created!"
            os.makedirs(dirs)
# 删除非空文件夹
def rmdirs(dirs):
    if not type(dirs) is types.StringType:
        for dir in dirs:
            if os.path.isdir(dir):
                shutil.rmtree(dir)
                print dir+"\t"*5+"deleted!"
    else:
        if os.path.isdir(dirs):
            shutil.rmtree(dirs)
            print dirs+"\t"*5+"deleted!"

def getModifyTime(dir):
    if(os.path.exists(dir)):
        timestamp = os.path.getmtime(dir)
        # print datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
        return datetime.datetime.fromtimestamp(timestamp)

# 是否最近某个时间范围之内的文件,天和秒共同决定
def after(file,days,seconds):
    now = datetime.datetime.now()
    timepoint = getModifyTime(file)
    delta= now-timepoint
    # print delta
    if(delta.days - days<0):
        return True
    elif(delta.days - days>0):
        return False
    else:
        return delta.seconds-seconds<=0
# 遍历文件夹
def walk(days,secs):
    for key in table.keys():
        root=key
        todir=table[key]

        if(os.path.isdir(root)):
            for parent,dirnames,filenames in os.walk(root):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
                # dirnames[:] = []
                # for dirname in  dirnames:                       #输出文件夹信息
                #     print "parent is:\t" + parent
                #     print  "dirname is:\t" + dirname

                for filename in filenames:                        #输出文件信息
                    # print "parent is:" + parent
                    # print "filename is:" + filename
                    # print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息

                    if after(os.path.join(parent,filename),days,secs):
                        print(os.path.join(parent,filename))
                        mkdirs(todir)
                        shutil.copyfile(os.path.join(parent,filename),os.path.join(todir,filename))
                        stat1=os.stat(os.path.join(parent,filename))
                        os.utime(os.path.join(todir,filename),(stat1[ST_CTIME], stat1[ST_MTIME]))

def run():
    # rmdirs(table.values())
    walk(1,30*60) #30分之内修改的文件

if __name__ == "__main__":
    run()

标签:python

收藏

0人收藏

支持

0

反对

0

发表评论