import os
import sys
import time
from shutil import Error
from shutil import copystat
from shutil import copy2
圖檔所處的絕對路徑,其中r表示去掉python的内部轉義
PicPath = r’E:\images’
CopyPath = r’E:\images\backup’
根據傳參判斷複制的目标位址是否存在如果不存在進行建立,并且執行複制操作
def copy_file(src_file, dst_dir):
if os.path.isdir(dst_dir):
pass
else:
os.makedirs(dst_dir)
copy2(src_file, dst_dir)
list dir
filelist = os.listdir(dst_dir)
周遊整個圖檔路徑底下的所有檔案并擷取其建立時間,根據建立時間進行複制操作
def walk_file(file_path):
for root, dirs, files in os.walk(file_path, topdown=False):
for name in files:
com_name = os.path.join(root, name)
t = os.stat(com_name)
copy_path_str = CopyPath + “\” + str(time.localtime(t.st_mtime).tm_year) + r"-" + str(
time.localtime(t.st_mtime).tm_mon)
copy_file(com_name, copy_path_str)
for name in dirs:
walk_file(name)
walk_file(PicPath)