Files
dic/00_gmep_file_copier.py

192 lines
6.8 KiB
Python
Raw Normal View History

2025-11-28 17:22:13 +09:00
import os
import shutil
from pathlib import Path
from typing import List, Tuple
class GMEPFileCopier:
"""답안 폴더 내부에서 .gmep 파일을 찾아 상위 폴더로 복사"""
"""
멀티미디어제작(곰픽)_004995-최정원\dpi_03-004995-최정원\dpi_03-004995-최정원.gmep 경로의 파일을
멀티미디어제작(곰픽)_004995-최정원\dpi_03-004995-최정원.gmep 경로로 복사
채점은 답안 폴더만 진행하므로 하위 폴더에 저장된 .gmep 파일을 상위 폴더로 복사하는 스크립트
"""
def __init__(self, base_path: str):
self.base_path = Path(base_path)
self.copied_files = []
self.errors = []
def find_and_copy_gmep_files(self) -> Tuple[int, int]:
"""
.gmep 파일을 찾아서 상위 폴더로 복사
Returns:
(성공 개수, 실패 개수)
"""
if not self.base_path.exists():
print(f"❌ 경로가 존재하지 않습니다: {self.base_path}")
return 0, 0
print(f"📁 검색 시작: {self.base_path}")
print("=" * 70)
# 각 학생 폴더 순회
for student_folder in self.base_path.iterdir():
if not student_folder.is_dir():
continue
print(f"\n🔍 검색 중: {student_folder.name}")
self._process_student_folder(student_folder)
# 결과 출력
self._print_summary()
return len(self.copied_files), len(self.errors)
def _process_student_folder(self, student_folder: Path):
"""학생 폴더의 하위 1단계 폴더만 검색"""
# 하위 1단계 폴더들만 검색
for subfolder in student_folder.iterdir():
if not subfolder.is_dir():
continue
# 해당 폴더에서 .gmep 파일 찾기
gmep_files = list(subfolder.glob("*.gmep"))
if gmep_files:
print(f" 📂 {subfolder.name}")
for gmep_file in gmep_files:
self._copy_file(gmep_file, student_folder)
def _copy_file(self, source: Path, destination_folder: Path):
"""파일 복사 실행"""
try:
destination = destination_folder / source.name
# 이미 같은 이름의 파일이 있는지 확인
if destination.exists():
# 파일명에 번호 추가
counter = 1
stem = source.stem
suffix = source.suffix
while destination.exists():
new_name = f"{stem}_{counter}{suffix}"
destination = destination_folder / new_name
counter += 1
shutil.copy2(source, destination)
self.copied_files.append({
'source': str(source),
'destination': str(destination),
'size': source.stat().st_size
})
print(f"{source.name}{destination_folder.name}/")
except Exception as e:
error_msg = f"파일 복사 실패: {source.name} - {str(e)}"
self.errors.append(error_msg)
print(f"{error_msg}")
def _print_summary(self):
"""작업 결과 요약 출력"""
print("\n" + "=" * 70)
print("📊 작업 완료 요약")
print("=" * 70)
print(f"✅ 복사 성공: {len(self.copied_files)}")
print(f"❌ 복사 실패: {len(self.errors)}")
if self.copied_files:
total_size = sum(f['size'] for f in self.copied_files)
print(f"📦 총 파일 크기: {self._format_size(total_size)}")
print("\n📝 복사된 파일 목록:")
for i, file_info in enumerate(self.copied_files, 1):
print(f" {i}. {Path(file_info['source']).name}")
print(f"{file_info['destination']}")
if self.errors:
print("\n⚠️ 오류 목록:")
for i, error in enumerate(self.errors, 1):
print(f" {i}. {error}")
@staticmethod
def _format_size(size_bytes: int) -> str:
"""바이트를 읽기 쉬운 형식으로 변환"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} TB"
def get_report(self) -> str:
"""작업 리포트를 문자열로 반환"""
report_lines = [
"=" * 70,
"GMEP 파일 복사 작업 리포트",
"=" * 70,
f"검색 경로: {self.base_path}",
f"복사 성공: {len(self.copied_files)}",
f"복사 실패: {len(self.errors)}",
""
]
if self.copied_files:
report_lines.append("복사된 파일:")
for file_info in self.copied_files:
report_lines.append(f" - {Path(file_info['source']).name}")
if self.errors:
report_lines.append("\n오류:")
for error in self.errors:
report_lines.append(f" - {error}")
return "\n".join(report_lines)
def main():
"""메인 실행 함수"""
# 기본 경로 설정
base_path = r"D:\project\GOM\DIC\output\2511\B\DPI"
# 사용자에게 경로 확인
print("🔧 GMEP 파일 복사 프로그램")
print("=" * 70)
print(f"검색 경로: {base_path}")
# 경로 변경 옵션
change_path = input("\n경로를 변경하시겠습니까? (y/n): ").strip().lower()
if change_path == 'y':
base_path = input("새 경로를 입력하세요: ").strip()
# 실행 확인
confirm = input("\n작업을 시작하시겠습니까? (y/n): ").strip().lower()
if confirm != 'y':
print("작업이 취소되었습니다.")
return
print("\n")
# 복사 작업 실행
copier = GMEPFileCopier(base_path)
success_count, error_count = copier.find_and_copy_gmep_files()
# 리포트 저장 옵션
if success_count > 0 or error_count > 0:
save_report = input("\n\n작업 리포트를 파일로 저장하시겠습니까? (y/n): ").strip().lower()
if save_report == 'y':
report_path = Path(base_path) / "gmep_copy_report.txt"
try:
report_path.write_text(copier.get_report(), encoding='utf-8')
print(f"✅ 리포트 저장 완료: {report_path}")
except Exception as e:
print(f"❌ 리포트 저장 실패: {e}")
print("\n프로그램을 종료합니다.")
if __name__ == "__main__":
main()