move_files.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import csv
  2. import os
  3. import shutil
  4. from pathlib import Path
  5. def default_desktop() -> Path:
  6. user_profile = Path(os.environ.get("USERPROFILE", str(Path.home())))
  7. return user_profile / "Desktop"
  8. def read_csv(csv_path: Path) -> list[dict[str, str]]:
  9. if not csv_path.is_file():
  10. raise ValueError(f"Die CSV-Datei existiert nicht: {csv_path}")
  11. with csv_path.open("r", newline="", encoding="latin-1") as csv_file:
  12. return list(csv.DictReader(csv_file, delimiter=";"))
  13. def move_files(
  14. files_csv: Path,
  15. clients_csv: Path,
  16. desktop_directory: Path | None = None,
  17. ) -> tuple[int, int, int]:
  18. desktop_directory = desktop_directory or default_desktop()
  19. client_rows = read_csv(clients_csv)
  20. client_names = {
  21. row.get("ParticipantName", "").strip(): row.get("Kunde", "").strip()
  22. for row in client_rows
  23. if row.get("ParticipantName", "").strip() and row.get("Kunde", "").strip()
  24. }
  25. moved_count = 0
  26. skipped_count = 0
  27. missing_client_count = 0
  28. for row in read_csv(files_csv):
  29. participant_name = row.get("ParticipantName", "").strip()
  30. source = Path(row.get("FilePath", "").strip())
  31. customer = client_names.get(participant_name)
  32. if not customer:
  33. missing_client_count += 1
  34. continue
  35. if not source.is_file():
  36. skipped_count += 1
  37. continue
  38. target_directory = desktop_directory / "PC-Visit" / customer
  39. target_directory.mkdir(parents=True, exist_ok=True)
  40. target = target_directory / source.name
  41. if source.resolve() == target.resolve() or target.exists():
  42. skipped_count += 1
  43. continue
  44. shutil.move(str(source), str(target))
  45. moved_count += 1
  46. return moved_count, skipped_count, missing_client_count