在現實生活中,我們可能遇到需要對檔案夾里的各種檔案進行處理,
假設存在一種需求:檔案夾里的檔案太多,我們需要抽取出某個時間段以前的檔案,
今天來實作下這個需求,
之前寫過一些關于檔案整理的,今天只是補充下,
python自動化辦公:檔案篇(自動整理檔案,一鍵完成)
時間模塊
python 日期和時間處理(time,datetime模塊講解)
os模塊
Python os.path() 模塊 詳解 附算例
re模塊
python :re模塊基本用法
獲取訪問時間
t = os.path.getatime(filePath)
獲取創建時間
t = os.path.getctime(filePath)
#獲取修改時間
t = os.path.getmtime(filePath)
準備作業
原始資料檔案夾

新建一個空白檔案夾

代碼:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: yudengwu(余登武)
# @Date : 2020/10/4
#@email:1344732766@qq.com
import os
import re
import time
from datetime import datetime
#首先定義規則,
pattern=re.compile(r'.+\.jpg|pdf')#定義檔案型別,尋找jpg,pdf
for root ,dirs,files in os.walk(r'C:\Users\Shineion\Desktop\yu'):
for name in files:
file_path=os.path.join(root,name)#包含路徑的檔案
if pattern.search(file_path) is not None :
#print(file_path)#匹配到的檔案 檔案路徑名
ctime=time.localtime(os.path.getctime(file_path))#創建時間
"""
#time.struct_time(tm_year=2020, tm_mon=9, tm_mday=20, tm_hour=13, tm_min=45, tm_sec=50, tm_wday=6,
tm_yday=264, tm_isdst=0)
"""
ctime=time.strftime("%Y/%m/%d %H:%M:%S",ctime)#字符型
"""
ctime
2020/09/20 13:45:50
"""
ctime=datetime.strptime(ctime, "%Y/%m/%d %H:%M:%S")#ctime 由字符型轉換為時間性
t1 = datetime(year=2020, month=10, day=26,hour = 7, minute = 9, second = 33)#自定義一個時間
#做差
if ctime<t1:
command_line = 'copy %s D:\\余登武測驗' % file_path.replace('/', '\\')#cmd復制命令
os.system(command_line)#呼叫cmd
print('復制成功')
結果和簡單決議
結果:

查看下zhengjian為什么沒有復制過來,發現屬性為JPG

修改檔案型別為
pattern=re.compile(r'.+\.jpg|pdf|JPG')
這次復制過來啦

修改日期為9月26日,即只要9月26日之前的檔案(PDF,jpg),

注意事項:有時檔案復制失敗 可能是檔案名的原因(有些檔案名即有中文,又有英文,容易失敗)
代碼決議
os.system(command_line)呼叫cmd來執行復制檔案,
cmd復制檔案命令:
copy 源檔案 目的路徑
time 時間不可以做差等計算,datetime可以
ctime=time.localtime(os.path.getctime(file_path))#創建時間
"""
#time.struct_time(tm_year=2020, tm_mon=9, tm_mday=20, tm_hour=13, tm_min=45, tm_sec=50, tm_wday=6,
tm_yday=264, tm_isdst=0)
"""
ctime=time.strftime("%Y/%m/%d %H:%M:%S",ctime)#字符型
"""
ctime
2020/09/20 13:45:50
"""
ctime=datetime.strptime(ctime, "%Y/%m/%d %H:%M:%S")#ctime 由字符型轉換為時間性
還可以洗掉檔案,不復制,
指令os.remove(檔案)

電氣工程的計算機萌新:余登武,
寫博文不容易,如果你覺得本文對你有用,請點個贊支持下,謝謝,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/157799.html
標籤:其他
