تمرين إعادة البناء
إنشاء نسخة احتياطية من ملف
أعد كتابة أداة Python تنسخ ملفاً واحداً مع لاحقة زمنية آمنة.
python
~12 دقيقة
مبتدئ
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
import argparse
import shutil
from datetime import datetime
from pathlib import Path
def backup_name(source: Path) -> str:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return f"{source.stem}_{timestamp}{source.suffix}"
def create_backup(source: Path, backup_dir: Path | None = None) -> Path:
if not source.is_file():
raise FileNotFoundError(f"Not a file: {source}")
target_dir = backup_dir or source.parent
target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / backup_name(source)
shutil.copy2(source, target)
return target
def main() -> None:
parser = argparse.ArgumentParser(description="Copy a file with a timestamp suffix.")
parser.add_argument("file", type=Path)
parser.add_argument("--dest", type=Path, help="Folder for the backup copy.")
args = parser.parse_args()
backup = create_backup(args.file, args.dest)
print(f"Backup created: {backup}")
if __name__ == "__main__":
main()اكتب هنا