一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python如何实现按日期归档文件 python实现按日期归档文件代码

时间:2021-01-30 编辑:袖梨 来源:一聚教程网

python如何实现按日期归档文件?本篇文章小编给大家分享一下python实现按日期归档文件代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

在工作过程中,data目录会一直接收文件,收到的文件放到一个大目录里不好判断是否漏收,也不利于检索;

所以写了个脚本,每天早上九点用Windows计划执行,将昨日这个文件夹内收到的文件全部归档,归档文件夹的名字就是昨天的日期,脚本及解释如下:

import os
import datetime
import shutil
 
# get file name
def get_datetime(i):
    d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split("-")
    timeoffile = d[0] + d[1] + d[2]
    return(timeoffile)
 
# new file
def get_newfile(i):
    filename = get_datetime(i)
    aimPath = 'C:\data\' + filename
    isExists=os.path.exists(aimPath)
    if not isExists:
        os.makedirs(aimPath)
        print(aimPath + 'ok!')
        return aimPath
    else:
        print(aimPath + 'file is exists!')
        return False
 
 
def delete_flie(filePath):
    for i,j,k in os.walk(filePath):
        n = 0
        while n < len(k):
            fileneed = filePath + '\' + k[n]
            if(os.path.exists(fileneed)):
                os.remove(fileneed)
            else:
                pass
            n = n + 1
     
# get file name and move
def get_filename(filePath):
    for i,j,k in os.walk(filePath):
        n = 0
        while n < len(k):
            fileneed = filePath + '\' + k[n]
            if(os.path.exists(fileneed)):
                shutil.move(fileneed,aimPath)
            else:
                pass   
            n = n + 1
 
# Monday special
def is_Monday():
    if datetime.datetime.now().weekday() == 0:
        return 3
    else:
        return 1
 
filePath = 'C:\data'
pos = is_Monday()
aimPath = get_newfile(pos)
get_filename(filePath)
delete_flie(filePath)

1.get_newfile

该函数调用get_datetime函数,获得指定日期,并按照YYYYMMDD的格式将日期拼接;

使用isExists,来对文件名是否存在进行校验,如果改文件夹不存在,则新建文件夹。

2.delete_flie

在移动结束后,删除原目录的文件;

在删除前要使用os.path.exists验证待删除文件是否存在。

3.get_filename

获取date文件夹内的文件名,并将其移动到新文件夹内;

在移动前要使用os.path.exists验证待移动文件是否存在。

4.is_Monday

周一的时候需要将周五、周六、周日的文件都放在以周五日期命名的文件夹中,所以使用这个函数来判断是星期几;

datetime.datetime.now().weekday()函数是0-6来表示周一-周五,所以值为0的时候,返回3;

这个函数的值将传给get_newfile,再调用get_datetime函数,通过控制这段的i,来控制生成的日期时间:

d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split("-")

注:shutil.copy会改变文件生成时间,不好对文件进行判断,所以要使用shutil.move移动文件

热门栏目