모듈명 : ffworker
# Module name is ffworker
# file : find, copy, move, delete
# folder : find, delete
from datetime import datetime, date, timedelta
import shutil as sh
import os, glob
def _printline():
print('='*49)
def _printstart(work_type,*message):
print('- Start '+work_type+' (',datetime.now().strftime('%Y-%m-%d %H:%M:%S'),') -')
if message:
_printline()
for msg in message:
if msg is not None:
print(msg)
_printline()
def _printend(work_type,count):
print(str(count)+' '+ work_type +' end.')
print('- End '+work_type+' (',datetime.now().strftime('%Y-%m-%d %H:%M:%S'),') -',end='\n\n')
#
# File Worker
#
class fileWorker():
def __init__(self, **kwargs):
# path : 작업 대상 경로
# files_list : 작업 대상 파일 리스트
# files_show : 파일 리스트 출력 여부
if 'path' in kwargs.keys():
self.path = kwargs['path']
else:
self.path = ''
if 'files_list' in kwargs.keys():
self.files_list = kwargs['files_list']
else:
self.files_list = []
if 'files_show' in kwargs.keys():
self.files_show = bool(kwargs['files_show'])
else:
self.files_show = False
## 복사/이동 ##
def __copymove(self,work_type,path,level):
count=0
for files in self.files_list:
for file in files:
path_split = file.split('\\')
# 폴더 생성
folder = path
for l in level:
folder = os.path.join(folder, path_split[l*-1])
if not os.path.exists(folder):
os.makedirs(folder)
# 복사/이동
file_name = path_split[-1]
file_all_path = os.path.join(folder,file_name)
if not os.path.exists(file_all_path):
if work_type == 'copy':
sh.copyfile(file,file_all_path)
print('copy >> '+ file_all_path)
elif work_type == 'move':
sh.move(file,file_all_path)
print('move >> '+ file_all_path)
count += 1
return count
## 파일 정보 ##
def file_meta(self, path):
ctime = os.path.getctime(path)
mtime = os.path.getmtime(path)
atime = os.path.getatime(path)
size = os.path.getsize(path)
return {'ctime':ctime, 'mtime':mtime,'atime':atime,'size':size}
## 파일 검색 ##
# find_files('jpg','txt','mp4') => .jpg, .txt, .mp4 확장자 파일 검색
def find_files(self, *args):
if args:
for a in args:
self.files_list.append(glob.glob(self.path + '/**/*.'+ a.split('.')[-1], recursive=True))
else:
self.files_list.append(glob.glob(self.path+'/**/*'))
if self.files_show:
print('>>> find files ')
for files in self.files_list:
for file in files:
print(file)
## 파일 복사 ##
# file_copy('D:/Temp',2) => D:/Temp로 파일들 복사하는데, 원본경로 오른쪽부터 2레벨 경로는 유지해서 복사
def file_copy(self,copy_path,*copy_level):
_printstart('file copy',"Path : "+copy_path)
_printend('file copy',self.__copymove('copy',copy_path,copy_level))
## 파일 이동 ##
# file_move('D:/Temp',2) => D:/Temp로 파일들 이동하는데, 원본경로 오른쪽부터 2레벨 경로는 유지해서 이동
def file_move(self, move_path,*move_level):
_printstart('file move','Path : '+move_path)
_printend('file move',self.__copymove('move',move_path,move_level))
## 파일 삭제 ##
def file_delete(self):
_printstart('file delete')
count=0
for files in self.files_list:
for file in files:
try:
if os.path.isfile(file):
os.remove(file)
count += 1
print('delete >> '+ file)
except:
print('error >> '+ file)
_printend('file delete',count)
#
# Folder Worker
#
class folderWorker():
def __init__(self, **kwargs):
# path : 작업 대상 경로
# folders_list : 작업 대상 폴더 리스트
# folders_show : 폴더 리스트 출력 여부
self.target = None
if 'path' in kwargs.keys():
self.path = kwargs['path']
else:
self.path = ''
if 'folders_list' in kwargs.keys():
self.folders_list = kwargs['folders_list']
else:
self.folders_list = []
if 'folders_show' in kwargs.keys():
self.folders_show = bool(kwargs['folders_show'])
else:
self.folders_show = False
## 복사/이동 ##
def __copymove(self, work_type, path, level):
count=0
return count
## 폴더 검색 ##
# find_folder(like='abc',period='-1') => abc문구가 포함되어 있거나, 폴더명(날짜)이 오늘-1일 이전인 폴더 검색
def find_folder(self, **kwargs):
# like : 폴더명에 특정 문구가 포함된 폴더 검색
# period : 폴더명(날짜) + n일 폴더 검색
# recursive : 하위 모두 검색
if 'recursive' in kwargs.keys():
recursive = bool(kwargs['recursive'])
else:
recursive = False
if 'like' in kwargs.keys():
like = kwargs['like']
self.target = 'Deleted constaining '+like
self.folders_list.append(glob.glob(self.path + '/*'+like+'*/', recursive=recursive))
if 'period' in kwargs.keys():
period = kwargs['period']
target_day = date.today() - timedelta(period*-1)
self.target = 'Storage period '+str(period*-1)+' days\nDeleted before '+ str(target_day.strftime('%Y-%m-%d'))+' (not include this day)'
for folder in glob.glob(self.path+'/????-??-??'):
folder_name = folder.split('\\')[-1]
if date(int(folder_name.split('-')[0]),int(folder_name.split('-')[1]),int(folder_name.split('-')[2])) < target_day:
self.folders_list.append([folder])
if self.folders_show:
print('>>> find folder')
for folders in self.folders_list:
for folder in folders:
print(folder)
## 폴더 복사 ##
def folder_copy(self, copy_path, *copy_level):
_printstart('folder copy','Path : ' + copy_path)
print("미구현..")
_printend('folder copy',self.__copymove('copy',copy_path, copy_level))
pass
## 폴더 이동 ##
def folder_move(self, move_path, *move_level):
_printstart('folder move','Path : ' + move_path)
print("미구현..")
_printend('folder move',self.__copymove('move',move_path, move_level))
pass
## 폴더 삭제 ##
# folder_delete(False) => 폴더들을 모두 삭제하는데 하위데이터가 존재하면 삭제하지 않음
def folder_delete(self,force):
# force : 강제삭제 true/false
_printstart('folder delete','Path : '+self.path, self.target)
count=0
for folders in self.folders_list:
for forder in folders:
try:
if not force:
# 하위 존재하면 삭제X
if len(os.listdir(forder)) < 1:
os.rmdir(forder)
count += 1
print('delete >> '+ forder)
else:
# 하위 상관없이 강제 삭제
sh.rmtree(forder)
count += 1
print('delete >> '+ forder)
except:
print('error >> '+ forder)
_printend('folder delete',count)
author = "ffworker"
'Language > Python' 카테고리의 다른 글
[Python] MAC에서 psycopg2 모듈 설치하기 (0) | 2021.12.13 |
---|