import os from pathlib import Path def ift_backup(base_dir=None): if base_dir is None: base_dir = 'E:\\IFT' source_path = Path(base_dir) / 'prod' target_path = base_dir + '/archive' for source_file in source_path.glob('*'): # print(source_file) file_temp = source_file.name if file_temp.count('_') == 2: prefix, filetype, timestamp = file_temp.split('_') year = timestamp[:4] month = timestamp[4:6] target = Path(f"{target_path}/{year}/{filetype}/{year}-{month}/{source_file.name}").absolute() os.makedirs(target.parent, exist_ok=True) if target.exists(): target.unlink() print(target) source_file.rename(target) if __name__ == '__main__': ift_backup()