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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
| import os
import shutil
from pathlib import Path
import json
from datetime import datetime
class FileUtilityError(Exception):
"""파일 유틸리티 전용 예외"""
pass
class FileOperationError(FileUtilityError):
"""파일 작업 오류"""
pass
class DirectoryError(FileUtilityError):
"""디렉토리 관련 오류"""
pass
class FileUtility:
"""견고한 파일 처리 유틸리티"""
def __init__(self, base_dir=None):
self.base_dir = Path(base_dir) if base_dir else Path.cwd()
self.operation_log = []
def log_operation(self, operation, success=True, error=None):
"""작업 로그 기록"""
log_entry = {
"timestamp": datetime.now().isoformat(),
"operation": operation,
"success": success,
"error": str(error) if error else None
}
self.operation_log.append(log_entry)
def safe_copy_file(self, source, destination):
"""안전한 파일 복사"""
try:
source_path = Path(source)
dest_path = Path(destination)
# 소스 파일 존재 확인
if not source_path.exists():
raise FileNotFoundError(f"소스 파일이 존재하지 않습니다: {source}")
if not source_path.is_file():
raise FileOperationError(f"소스가 파일이 아닙니다: {source}")
# 대상 디렉토리 생성
dest_path.parent.mkdir(parents=True, exist_ok=True)
# 파일 크기 확인 (너무 큰 파일 방지)
file_size = source_path.stat().st_size
if file_size > 100 * 1024 * 1024: # 100MB 제한
raise FileOperationError(f"파일이 너무 큽니다: {file_size / 1024 / 1024:.1f}MB")
# 백업 생성 (대상 파일이 이미 존재하는 경우)
if dest_path.exists():
backup_path = dest_path.with_suffix(dest_path.suffix + '.backup')
shutil.copy2(dest_path, backup_path)
print(f"기존 파일 백업: {backup_path}")
# 파일 복사
shutil.copy2(source_path, dest_path)
# 복사 검증
if not dest_path.exists():
raise FileOperationError("파일 복사가 완료되지 않았습니다.")
if source_path.stat().st_size != dest_path.stat().st_size:
raise FileOperationError("복사된 파일 크기가 다릅니다.")
self.log_operation(f"파일 복사: {source} → {destination}")
print(f"✅ 파일 복사 완료: {source} → {destination}")
return True
except FileNotFoundError as e:
self.log_operation(f"파일 복사 실패: {source} → {destination}", False, e)
raise
except PermissionError as e:
error_msg = f"권한 부족: {e}"
self.log_operation(f"파일 복사 실패: {source} → {destination}", False, error_msg)
raise FileOperationError(error_msg) from e
except OSError as e:
error_msg = f"파일 시스템 오류: {e}"
self.log_operation(f"파일 복사 실패: {source} → {destination}", False, error_msg)
raise FileOperationError(error_msg) from e
def safe_delete_file(self, file_path, use_recycle_bin=True):
"""안전한 파일 삭제"""
try:
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"파일이 존재하지 않습니다: {file_path}")
if not path.is_file():
raise FileOperationError(f"파일이 아닙니다: {file_path}")
# 휴지통 사용 옵션
if use_recycle_bin:
# 실제 구현에서는 send2trash 라이브러리 사용 권장
recycle_dir = self.base_dir / ".recycle_bin"
recycle_dir.mkdir(exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
recycled_name = f"{path.stem}_{timestamp}{path.suffix}"
recycled_path = recycle_dir / recycled_name
shutil.move(str(path), str(recycled_path))
print(f"🗑️ 파일을 휴지통으로 이동: {recycled_path}")
else:
path.unlink()
print(f"🗑️ 파일 완전 삭제: {file_path}")
self.log_operation(f"파일 삭제: {file_path}")
return True
except FileNotFoundError as e:
self.log_operation(f"파일 삭제 실패: {file_path}", False, e)
raise
except PermissionError as e:
error_msg = f"권한 부족: {e}"
self.log_operation(f"파일 삭제 실패: {file_path}", False, error_msg)
raise FileOperationError(error_msg) from e
def create_directory_structure(self, structure_dict, base_path=None):
"""디렉토리 구조 생성"""
if base_path is None:
base_path = self.base_dir
else:
base_path = Path(base_path)
try:
for name, content in structure_dict.items():
current_path = base_path / name
if isinstance(content, dict):
# 디렉토리 생성 후 재귀 호출
current_path.mkdir(exist_ok=True)
print(f"📁 디렉토리 생성: {current_path}")
self.create_directory_structure(content, current_path)
elif isinstance(content, str):
# 파일 생성
current_path.parent.mkdir(parents=True, exist_ok=True)
current_path.write_text(content, encoding='utf-8')
print(f"📄 파일 생성: {current_path}")
else:
# 빈 파일 생성
current_path.parent.mkdir(parents=True, exist_ok=True)
current_path.touch()
print(f"📄 빈 파일 생성: {current_path}")
self.log_operation(f"디렉토리 구조 생성: {base_path}")
return True
except PermissionError as e:
error_msg = f"권한 부족: {e}"
self.log_operation(f"디렉토리 구조 생성 실패: {base_path}", False, error_msg)
raise DirectoryError(error_msg) from e
except OSError as e:
error_msg = f"파일 시스템 오류: {e}"
self.log_operation(f"디렉토리 구조 생성 실패: {base_path}", False, error_msg)
raise DirectoryError(error_msg) from e
def backup_directory(self, source_dir, backup_name=None):
"""디렉토리 백업"""
try:
source_path = Path(source_dir)
if not source_path.exists():
raise DirectoryError(f"소스 디렉토리가 존재하지 않습니다: {source_dir}")
if not source_path.is_dir():
raise DirectoryError(f"소스가 디렉토리가 아닙니다: {source_dir}")
# 백업 이름 생성
if backup_name is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"{source_path.name}_backup_{timestamp}"
backup_path = self.base_dir / "backups" / backup_name
backup_path.parent.mkdir(parents=True, exist_ok=True)
# 디렉토리 복사
shutil.copytree(source_path, backup_path, dirs_exist_ok=True)
# 백업 정보 저장
backup_info = {
"source": str(source_path),
"backup_path": str(backup_path),
"timestamp": datetime.now().isoformat(),
"file_count": sum(1 for _ in backup_path.rglob('*') if _.is_file())
}
info_file = backup_path / "backup_info.json"
info_file.write_text(json.dumps(backup_info, indent=2, ensure_ascii=False))
self.log_operation(f"디렉토리 백업: {source_dir} → {backup_path}")
print(f"✅ 백업 완료: {backup_path}")
return backup_path
except shutil.Error as e:
error_msg = f"백업 과정에서 오류 발생: {e}"
self.log_operation(f"디렉토리 백업 실패: {source_dir}", False, error_msg)
raise DirectoryError(error_msg) from e
def get_operation_log(self):
"""작업 로그 반환"""
return self.operation_log.copy()
def save_operation_log(self, filename=None):
"""작업 로그 파일로 저장"""
try:
if filename is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"file_operations_{timestamp}.json"
log_file = self.base_dir / filename
log_file.write_text(
json.dumps(self.operation_log, indent=2, ensure_ascii=False),
encoding='utf-8'
)
print(f"📝 작업 로그 저장: {log_file}")
return log_file
except Exception as e:
raise FileOperationError(f"로그 저장 실패: {e}") from e
# 파일 유틸리티 사용 예제
def demo_file_utility():
"""파일 유틸리티 데모"""
try:
# 유틸리티 생성
util = FileUtility("./file_demo")
# 테스트 구조 생성
test_structure = {
"documents": {
"reports": {
"2024_report.txt": "2024년 보고서 내용"
},
"notes": {
"meeting_notes.txt": "회의 내용\n- 항목 1\n- 항목 2"
}
},
"images": {},
"backup": {},
"readme.txt": "프로젝트 설명 파일"
}
print("📁 디렉토리 구조 생성 중...")
util.create_directory_structure(test_structure)
# 파일 복사 테스트
print("\n📋 파일 복사 테스트...")
util.safe_copy_file(
"./file_demo/readme.txt",
"./file_demo/backup/readme_backup.txt"
)
# 백업 테스트
print("\n💾 디렉토리 백업 테스트...")
backup_path = util.backup_directory("./file_demo/documents")
# 작업 로그 저장
print("\n📝 작업 로그 저장...")
log_file = util.save_operation_log()
# 로그 출력
print("\n📊 작업 로그:")
for i, log in enumerate(util.get_operation_log(), 1):
status = "✅" if log["success"] else "❌"
print(f" {i}. {status} {log['operation']} ({log['timestamp'][:19]})")
print(f"\n🎉 데모 완료! 생성된 파일들을 확인해보세요.")
print(f" - 메인 디렉토리: ./file_demo")
print(f" - 백업: {backup_path}")
print(f" - 로그: {log_file}")
except (FileUtilityError, FileOperationError, DirectoryError) as e:
print(f"❌ 파일 유틸리티 오류: {e}")
except Exception as e:
print(f"❌ 예상치 못한 오류: {type(e).__name__}: {e}")
# 데모 실행
if __name__ == "__main__":
demo_file_utility()
|