1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import os import shutil from datetime import datetime
src_dir='/data/test' dest_dir='/backup/'
if not os.path.exists(src_dir): os.makedirs(src_dir)
os.makedirs(os.path.join(src_dir,'subdir1'),exist_ok=True) os.makedirs(os.path.join(src_dir,'subdir2'),exist_ok=True) with open(os.path.join(src_dir,'file1.txt'),'w') as f: f.write('file1 test') with open(os.path.join(src_dir,'file2.txt'),'w') as f: f.write('file2 test') with open(os.path.join(src_dir,'file3.txt'),'w') as f: f.write('file3 test')
if not os.path.exists(dest_dir): os.makedirs(dest_dir)
timestamp=datetime.now().strftime('%Y%m%d_%H%M%S')
backup_dir=os.path.join(dest_dir,f'backup-{timestamp}') if not os.path.exists(backup_dir): os.makedirs(backup_dir)
for item in os.listdir(src_dir): src_file = os.path.join(src_dir,item) dest_file = os.path.join(backup_dir,item) if os.path.isdir(src_file): shutil.copytree(src_file,backup_dir,dirs_exist_ok=True,copy_function=shutil.copy2) if os.path.isfile(src_file): shutil.copy2(src_file,backup_dir)
print(f"备份完成,文件已复制到{dest_dir}")
|