处理文件方法

import os
import datetime
from glob2 import glob
from ntpath import relpath
import errno
# from MyTest3 import file
# from MyTest3 import config
class HandleFileClass(object):
code_name=None
program_folder=None

abs_path=[]
cur_fun=None
param=None
def __init__(self):
code_name=os.path.basename(__file__)
program_folder = os.path.dirname(os.path.realpath(__file__))
self.code_name=code_name
self.program_folder=program_folder
print('[Progress]:{0:s}'.format(code_name))
print('[position]:{0:s}'.format(program_folder))
def findDir(self,name,path,mkdir_flag=False,mode=777): #Determine whether the file path exists
if os.path.exists(path):
if not os.path.isdir(path):
print('ERROR:{0:s} not a dir:{1:s}'.format(name,os.path.basename(path)))
return False
else:
# print('{0:s}:{1:s}'.format(name,os.path.realpath(path)))
return True
else:
print('ERROR:{0:s} not exist:{1:s}'.format(name,path))
return False
def deleteAllFile(self,dir_path):#Delete all files in the path
for i in glob(os.path.join(dir_path,'*')):
#check
filename=os.path.basename(i)
if i:
if str.index(filename,'@')!=-1:
os.remove(i, dir_fd=None)
print('[Operation]:Delete {0:s} From {1:s}'.format(filename,dir_path))
else:
print('Please Check the delete path.')
else:
pass
def iterFindFile(self,path,findFileName,loaderList):#Iterecte 'path' and find 'findFileName' where in 'loaderlist'
try:
if not self.findDir("FROM PATH", path):
return
for i in os.listdir(path):
if (loaderList and loaderList.count(i)==1) or set(loaderList).intersection(path.split('\\')):
if os.path.isdir(os.path.join(path,i)):
# print(i)
self.iterFindFile(os.path.join(path,i),findFileName,loaderList)
elif os.path.basename(i)==str(findFileName):
abspath=os.path.abspath(os.path.join(path,i))
self.abs_path.append(abspath)
# print('file:{0}; path:{1}'.format(findfile,relpath))
else:
continue
else:
continue
return self.abs_path
except Exception as ex:
print(ex)
def CopyFile(self,from_path,to_path,findFileName,lst_focusLoader):#copy file from 'from_path' to 'to_path'
self.cur_fun='CopyFile'
self.param=dict(zip(['from_path','to_path'],[from_path,to_path]))
print('[Function]:{0:s}'.format(self.cur_fun))
print('[Parameter]:\n\t From:{from_path:s}\n\t To:{to_path:s}'.format(**self.param))

lst_findFilePath=self.iterFindFile(from_path,findFileName,lst_focusLoader)
try:
if not lst_findFilePath:
return
if not self.findDir(' TO_DIR',to_path):
os.mkdir(to_path,777)
else:
self.deleteAllFile(to_path)
for i in lst_findFilePath:
# print(i)
oldFileName=os.path.basename(i)
relpath=os.path.relpath(i, from_path)
newFileName=str(relpath.replace("\\", "@"))
# print(newFileName)
shutil.copy2(i, to_path)
os.rename( os.path.join(to_path,oldFileName), os.path.join(to_path,newFileName) )
print('[Operation]:Copy:{0} From:.\{1} To:target and Rename:{2}'.format(oldFileName,relpath,newFileName))
return True
except Exception as ex:
print(ex)
return False
finally:
self.code_name=None
self.program_folder=None
self.abs_path.clear()
self.cur_fun=None
self.param=None
print('-----------------------------------------------------------------------------------')
def MoveFile(self,src,dst, sub_folder=True):
if not os.path.exists(src):
raise Exception("Source: '{0}' isn't exists.".format(src))
if not os.path.exists(dst):
os.makedirs(dst, mode=777)
if dst: # C0.02
_dst = dst#./Data/Archive
#if exist src file then remove
if os.path.join(dst,os.path.basename(src)):
print('[Operation]:Move file:<{0}> To<{1}>'.format(src,os.path.join(dst,os.path.basename(src))))
return shutil.move(src, os.path.join(dst,os.path.basename(src)))
try:
print('[Operation]:Move file:<{0}> To<{1}>'.format(src,_dst))
return shutil.move(src, _dst)
except IOError as ex:
if ex.errno == errno.ENOENT: # No such file or directory
# try creating parent directories
os.makedirs(os.path.dirname(_dst))
return shutil.move(src, _dst, copy_function=shutil.copy2)
elif ex.errno == errno.EEXIST: # File exists
return shutil.move(src, os.path.join(_dst, os.path.basename(src) + ".{:%Y%m%d_%H%M%S.%f}".format(datetime.datetime.now())), copy_function=shutil.copy2)
else:
raise ex
else:
if os.path.isfile(src):

return os.remove(src)
else:
return shutil.rmtree(src, ignore_errors=True)
import shutil
if __name__ == '__main__':
# program_folder = os.path.dirname(os.path.realpath(__file__))
# to_path=os.path.join(program_folder,"Loader_Config")
c=HandleFileClass()

FROM_PATH='D:\software\eclipse\eclipse-workspace\EDAETL'

TO_PATH='.\Data\Source\ErrorFiles'
findFileName='error.log'
lst_focusLoader=['DFS_SUMLoader','DfsDispatch','DFSLoaders','EdcDbLoader','M2MESLoaders','MESLoaders','OtherLoaders','SPCLoaders']
# c.CopyFile(FROM_PATH,TO_PATH,findFileName,lst_focusLoader)

TO_PATH2='.\Data\Source\ConfigFiles'
findFileName2='config.py'
lst_focusLoader2=['DFS_SUMLoader','DfsDispatch','DFSLoaders','EdcDbLoader','M2MESLoaders','MESLoaders','OtherLoaders','SPCLoaders']
# c.CopyFile(FROM_PATH,TO_PATH2,findFileName2,lst_focusLoader2)

TO_PATH3='.\Data\Source\DispatchFiles'
findFileName3='dispatch_config.json'
lst_focusLoader3=['DfsDispatch']
# c.CopyFile(FROM_PATH,TO_PATH3,findFileName3,lst_focusLoader3)

# file=open('./Data/Source/DispatchFiles/DfsDispatch@dispatch_config.json')
# print(file.name)
#
ARCHIVE_FOLDER = './Data/Archive/ConfigFiles'
ERROR_FOLDER = './Data/Error/ConfigFiles'
SOURCE_FOLDER = './Data/Source/ConfigFiles/DfsDispatch@config.py'
# c.MoveFile(SOURCE_FOLDER,ERROR_FOLDER)


TO_PATH='./Data/Archive/ErrorFiles'
FROM_PATH='D:\software\eclipse\eclipse-workspace\EDAETL'
FIND_FILENAME='error.log'
LST_FOCUSDIR=['DFS_SUMLoader','DfsDispatch','DFSLoaders','EdcDbLoader','M2MESLoaders','MESLoaders','OtherLoaders','SPCLoaders']
c.CopyFile(FROM_PATH,TO_PATH,FIND_FILENAME,LST_FOCUSDIR)

posted @ 2023-01-31 10:07  咪嗞哈嘻  阅读(13)  评论(0编辑  收藏  举报