Python 파일 자동화 | 파일 정리, 이름 변경, 백업 자동화
이 글의 핵심
Python 파일 자동화에 대한 실전 가이드입니다. 파일 정리, 이름 변경, 백업 자동화 등을 예제와 함께 상세히 설명합니다.
들어가며
”반복 작업은 자동화하세요”
Python으로 파일 작업을 자동화하면 시간을 크게 절약할 수 있습니다.
1. 파일 찾기
특정 확장자 파일 찾기
pathlib.Path.glob과 **는 폴더 서랍을 열어 같은 확장자만 골라 담는 작업을 재귀적으로 해 줍니다. 예를 들어 프로젝트 전체에서 .pdf만 모을 때 수작업으로 찾기보다 훨씬 빠릅니다.
from pathlib import Path
def find_files(directory, extension):
"""특정 확장자 파일 찾기"""
path = Path(directory)
return list(path.glob(f'**/*.{extension}'))
# 사용
pdf_files = find_files('.', 'pdf')
for file in pdf_files:
print(file)
조건부 파일 찾기
import os
from datetime import datetime, timedelta
def find_old_files(directory, days=30):
"""N일 이상 된 파일 찾기"""
cutoff = datetime.now() - timedelta(days=days)
old_files = []
for root, dirs, files in os.walk(directory):
for file in files:
filepath = Path(root) / file
mtime = datetime.fromtimestamp(filepath.stat().st_mtime)
if mtime < cutoff:
old_files.append(filepath)
return old_files
# 사용
old_files = find_old_files('.', days=90)
print(f"{len(old_files)}개의 오래된 파일")
2. 파일 이름 변경
일괄 이름 변경
from pathlib import Path
def rename_files(directory, old_pattern, new_pattern):
"""파일 이름 일괄 변경"""
path = Path(directory)
for file in path.glob('*'):
if old_pattern in file.name:
new_name = file.name.replace(old_pattern, new_pattern)
file.rename(file.parent / new_name)
print(f"{file.name} → {new_name}")
# 사용
rename_files('.', 'old_', 'new_')
순번 추가
def add_numbers(directory, extension):
"""파일에 순번 추가"""
path = Path(directory)
files = sorted(path.glob(f'*.{extension}'))
for i, file in enumerate(files, 1):
new_name = f"{i:03d}_{file.name}"
file.rename(file.parent / new_name)
print(f"{file.name} → {new_name}")
# 사용
add_numbers('./images', 'jpg')
# photo.jpg → 001_photo.jpg
3. 파일 정리
확장자별 폴더 정리
import shutil
from pathlib import Path
def organize_files(directory):
"""확장자별로 폴더 정리"""
path = Path(directory)
for file in path.iterdir():
if file.is_file():
# 확장자 추출
ext = file.suffix[1:] # .jpg → jpg
if ext:
# 폴더 생성
target_dir = path / ext
target_dir.mkdir(exist_ok=True)
# 파일 이동
shutil.move(str(file), str(target_dir / file.name))
print(f"{file.name} → {ext}/")
# 사용
organize_files('./downloads')
4. 자동 백업
백업 스크립트
import shutil
from pathlib import Path
from datetime import datetime
def backup_directory(source, backup_root):
"""디렉토리 백업"""
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f"backup_{timestamp}"
backup_path = Path(backup_root) / backup_name
# 백업 실행
shutil.copytree(source, backup_path)
print(f"백업 완료: {backup_path}")
# 압축
shutil.make_archive(str(backup_path), 'zip', backup_path)
shutil.rmtree(backup_path) # 원본 폴더 삭제
print(f"압축 완료: {backup_path}.zip")
# 사용
backup_directory('./project', './backups')
오래된 백업 삭제
def cleanup_old_backups(backup_dir, keep_count=5):
"""최신 N개만 유지"""
path = Path(backup_dir)
backups = sorted(path.glob('backup_*.zip'), key=lambda x: x.stat().st_mtime)
# 오래된 것 삭제
for backup in backups[:-keep_count]:
backup.unlink()
print(f"삭제: {backup.name}")
# 사용
cleanup_old_backups('./backups', keep_count=5)
5. 중복 파일 찾기
해시 기반 중복 검사
import hashlib
from collections import defaultdict
def find_duplicates(directory):
"""중복 파일 찾기 (MD5 해시)"""
hashes = defaultdict(list)
for file in Path(directory).rglob('*'):
if file.is_file():
# 파일 해시 계산
with open(file, 'rb') as f:
file_hash = hashlib.md5(f.read()).hexdigest()
hashes[file_hash].append(file)
# 중복 파일 출력
duplicates = {h: files for h, files in hashes.items() if len(files) > 1}
for hash_val, files in duplicates.items():
print(f"\n중복 그룹 ({hash_val[:8]}...):")
for file in files:
print(f" - {file}")
return duplicates
# 사용
duplicates = find_duplicates('./documents')
6. 실전 예제
로그 파일 정리 스크립트
from pathlib import Path
import gzip
from datetime import datetime, timedelta
def cleanup_logs(log_dir, archive_days=7, delete_days=30):
"""
로그 파일 정리:
- 7일 이상: 압축
- 30일 이상: 삭제
"""
path = Path(log_dir)
now = datetime.now()
for log_file in path.glob('*.log'):
mtime = datetime.fromtimestamp(log_file.stat().st_mtime)
age = (now - mtime).days
if age >= delete_days:
# 삭제
log_file.unlink()
print(f"삭제: {log_file.name} ({age}일)")
elif age >= archive_days:
# 압축
gz_path = log_file.with_suffix('.log.gz')
with open(log_file, 'rb') as f_in:
with gzip.open(gz_path, 'wb') as f_out:
f_out.writelines(f_in)
log_file.unlink()
print(f"압축: {log_file.name} → {gz_path.name}")
# 사용
cleanup_logs('./logs', archive_days=7, delete_days=30)
백업·드라이런·로그로 실수 줄이기
파일을 지우거나 옮기는 스크립트는 한 번 잘못 돌리면 되돌리기 어렵습니다. 먼저 대상만 출력하는 테스트 모드로 범위를 확인하고, 중요한 디렉터리는 복사본을 둔 뒤 실행하는 습관이 안전합니다. 예외는 PermissionError처럼 원인이 다른 종류로 나누어 잡으면 디버깅이 빨라집니다.
# ✅ 안전한 파일 작업
# 1. 백업 먼저
# 2. 테스트 모드 (실제 작업 전 확인)
# 3. 로깅
# ✅ 에러 처리
try:
shutil.move(src, dst)
except PermissionError:
print("권한 없음")
except FileNotFoundError:
print("파일 없음")
# ✅ 진행 상황 표시
from tqdm import tqdm
for file in tqdm(files, desc="처리 중"):
process(file)
정리
핵심 요약
- 파일 찾기: glob, rglob
- 이름 변경: rename()
- 파일 이동: shutil.move()
- 백업: copytree(), make_archive()
- 중복 검사: 해시 비교
다음 단계
- 웹 스크래핑
- 작업 스케줄링
관련 글
- Python 파일 처리 | 읽기, 쓰기, CSV, JSON 완벽 정리