본문 바로가기

파이썬3

[개인용] 디렉토리 내의 특정 패턴의 파일들 백업하는 기능

728x90
반응형

아래에 있는 기능은 작업 중에 썼던 스크립트 파일들을 복사하기 위한 스크립트임.

'''
각 디렉토리에서 python script를 저장하기 위한 스크립트.
오로지 백업하는 것은 스크립트만임.
'''
#파라미터 및 라이브러리 셋팅
params={
    'top-dir':'data' # 가장 최상위 디렉토리의 패턴
    ,'2nd-dir':'/project/sjoh' # 2번 째 디렉토리의 패턴
    ,'script-backup-dir':'/data03/project/sjoh/00_archive/sjoh-backup/script-backup'
}

# 데이터 경로 탐색
import os
import subprocess as sbp
from tqdm import tqdm
def find_files_to_be_backup(params,file_pattern=['.py','.ipynb','.r','.R']):
    todir=os.listdir('/')
    todir=['/'+d for d in todir if params['top-dir'] in d]
    todir=[d+params['2nd-dir'] for d in todir]
    # search the python and ipynb
    file_list=[]
    for d in tqdm(todir,desc='Listing files to be back-up'): #d=todir[0]
        if os.path.exists(d)==False:
            continue
        else:
            print('Files in ',d)
            for fp in file_pattern: #fp=file_pattern[1]
                result=sbp.check_output(['find',d,'-name',f'*{fp}'])
                result=str(result)
                files=result.split('\\n')
                files=[i.replace("b'","") for i in files]
                file_list+=files
    file_list=[i for i in file_list if len(i)>2]
    print('Number of files :',len(file_list))
    return file_list


indata={}
indata['file']=find_files_to_be_backup(params=params,file_pattern=['.py','.ipynb','.r','.R'])


# backupping
if os.path.exists(params['script-backup-dir'])==False:
    os.makedirs(params['script-backup-dir'])

def do_backup(x,backup_dir):
    for file in tqdm(x,desc='Copying the files'): #file=x[0]
        filename=file.split('/')[-1]
        original_dir_path=backup_dir+'/'.join(file.split('/')[:-1])
        if os.path.exists(original_dir_path)==False:
            os.makedirs(original_dir_path)
        # Check two points.
        # 1) whether the backup-file exists in backup-dir
        # 2) whether the backup-file and original-file have identical file-size
        backup_file_path=original_dir_path+f'/{filename}'
        if os.path.exists(backup_file_path):
            backup_file_size=os.path.getsize(backup_file_path)
            original_file_size=os.path.getsize(file)
            if backup_file_size==original_file_size:
                continue
        # copy the path
        cmd=f'cp {file} {original_dir_path}/'
        sbp.call(cmd,shell=True)
    print('Copying finished')



do_backup(x=indata['file'],backup_dir=params['script-backup-dir'])
728x90
반응형