python實(shí)現(xiàn)按日期歸檔文件
在工作過(guò)程中,data目錄會(huì)一直接收文件,收到的文件放到一個(gè)大目錄里不好判斷是否漏收,也不利于檢索;
所以寫了個(gè)腳本,每天早上九點(diǎn)用Windows計(jì)劃執(zhí)行,將昨日這個(gè)文件夾內(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,來(lái)對(duì)文件名是否存在進(jìn)行校驗(yàn),如果改文件夾不存在,則新建文件夾。
2.delete_flie在移動(dòng)結(jié)束后,刪除原目錄的文件;
在刪除前要使用os.path.exists驗(yàn)證待刪除文件是否存在。
3.get_filename獲取date文件夾內(nèi)的文件名,并將其移動(dòng)到新文件夾內(nèi);
在移動(dòng)前要使用os.path.exists驗(yàn)證待移動(dòng)文件是否存在。
4.is_Monday周一的時(shí)候需要將周五、周六、周日的文件都放在以周五日期命名的文件夾中,所以使用這個(gè)函數(shù)來(lái)判斷是星期幾;
datetime.datetime.now().weekday()函數(shù)是0-6來(lái)表示周一-周五,所以值為0的時(shí)候,返回3;
這個(gè)函數(shù)的值將傳給get_newfile,再調(diào)用get_datetime函數(shù),通過(guò)控制這段的i,來(lái)控制生成的日期時(shí)間:
d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split('-')
注:shutil.copy會(huì)改變文件生成時(shí)間,不好對(duì)文件進(jìn)行判斷,所以要使用shutil.move移動(dòng)文件
以上就是python實(shí)現(xiàn)按日期歸檔文件的詳細(xì)內(nèi)容,更多關(guān)于python歸檔文件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)3. .NET6打包部署到Windows Service的全過(guò)程4. Vue element ui用戶展示頁(yè)面的實(shí)例5. 如何在jsp界面中插入圖片6. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)7. Ajax返回值類型與用法實(shí)例分析8. 使用FormData進(jìn)行Ajax請(qǐng)求上傳文件的實(shí)例代碼9. asp批量添加修改刪除操作示例代碼10. css代碼優(yōu)化的12個(gè)技巧
