溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在python中根據(jù)日期對文件進行歸檔

發(fā)布時間:2021-01-30 13:39:00 來源:億速云 閱讀:236 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)怎么在python中根據(jù)日期對文件進行歸檔,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

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

  該函數(shù)調(diào)用get_datetime函數(shù),獲得指定日期,并按照YYYYMMDD的格式將日期拼接;

  使用isExists,來對文件名是否存在進行校驗,如果改文件夾不存在,則新建文件夾。

2.delete_flie

  在移動結(jié)束后,刪除原目錄的文件;

  在刪除前要使用os.path.exists驗證待刪除文件是否存在。

3.get_filename

  獲取date文件夾內(nèi)的文件名,并將其移動到新文件夾內(nèi);

  在移動前要使用os.path.exists驗證待移動文件是否存在。

4.is_Monday

  周一的時候需要將周五、周六、周日的文件都放在以周五日期命名的文件夾中,所以使用這個函數(shù)來判斷是星期幾;

  datetime.datetime.now().weekday()函數(shù)是0-6來表示周一-周五,所以值為0的時候,返回3;

  這個函數(shù)的值將傳給get_newfile,再調(diào)用get_datetime函數(shù),通過控制這段的i,來控制生成的日期時間:

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

注:shutil.copy會改變文件生成時間,不好對文件進行判斷,所以要使用shutil.move移動文件

看完上述內(nèi)容,你們對怎么在python中根據(jù)日期對文件進行歸檔有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI