温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中根据日期对文件进行归档

发布时间:2021-01-30 13:39:00 来源:亿速云 阅读:224 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关怎么在python中根据日期对文件进行归档,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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移动文件

看完上述内容,你们对怎么在python中根据日期对文件进行归档有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI