python實現(xiàn)按日期歸檔文件
在工作過程中,data目錄會一直接收文件,收到的文件放到一個大目錄里不好判斷是否漏收,也不利于檢索;
所以寫了個腳本,每天早上九點用Windows計劃執(zhí)行,將昨日這個文件夾內(nèi)收到的文件全部歸檔,歸檔文件夾的名字就是昨天的日期,腳本及解釋如下:
import osimport datetimeimport shutil # get file namedef get_datetime(i): d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split('-') timeoffile = d[0] + d[1] + d[2] return(timeoffile) # new filedef 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 = 0while n < len(k): fileneed = filePath + ’’ + k[n] if(os.path.exists(fileneed)):os.remove(fileneed) else:pass n = n + 1 # get file name and movedef get_filename(filePath): for i,j,k in os.walk(filePath):n = 0while n < len(k): fileneed = filePath + ’’ + k[n] if(os.path.exists(fileneed)):shutil.move(fileneed,aimPath) else:pass n = n + 1 # Monday specialdef 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在移動結束后,刪除原目錄的文件;
在刪除前要使用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移動文件
以上就是python實現(xiàn)按日期歸檔文件的詳細內(nèi)容,更多關于python歸檔文件的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. IntelliJ IDEA導入jar包的方法2. Python requests庫參數(shù)提交的注意事項總結3. 詳談ajax返回數(shù)據(jù)成功 卻進入error的方法4. python ansible自動化運維工具執(zhí)行流程5. vue-electron中修改表格內(nèi)容并修改樣式6. JavaScript中l(wèi)ayim之整合右鍵菜單的示例代碼7. python操作mysql、excel、pdf的示例8. 匹配模式 - XSL教程 - 49. 通過Python pyecharts輸出保存圖片代碼實例10. javascript實現(xiàn)雪花飄落效果
