[2026] Python 파일 자동화 | 파일 정리, 이름 변경, 백업 자동화

[2026] Python 파일 자동화 | 파일 정리, 이름 변경, 백업 자동화

이 글의 핵심

Python 파일 자동화: 파일 정리, 이름 변경, 백업 자동화. 파일 찾기·파일 이름 변경.

들어가며

”반복 작업은 자동화하세요”

Python으로 파일 작업을 자동화하면 시간을 크게 절약할 수 있습니다.

실무 활용 사례: 데이터 분석, 웹 개발, 자동화 프로젝트에서 실제로 사용한 패턴과 코드를 바탕으로 정리했습니다. 초보자가 흔히 겪는 오류와 해결법을 포함합니다.

실무에서 느낀 Python의 매력

처음 Python을 배울 때는 “이게 정말 프로그래밍 언어인가?” 싶을 정도로 간결했습니다. C++에서 10줄로 작성하던 코드가 Python에서는 2~3줄로 끝나는 경우가 많았죠. 특히 데이터 분석 프로젝트를 진행하면서 Pandas와 NumPy의 강력함을 체감했습니다. 엑셀로 몇 시간 걸리던 작업이 Python 스크립트로는 몇 초 만에 끝나는 걸 보고 동료들이 놀라워했던 기억이 납니다. 하지만 처음부터 순탄하지만은 않았습니다. 들여쓰기 하나 잘못해서 몇 시간을 헤맨 적도 있고, 가상환경 설정이 꼬여서 프로젝트 전체를 다시 시작한 적도 있습니다. 이런 시행착오를 겪으며 깨달은 건, 환경 설정을 처음부터 제대로 하는 것이 얼마나 중요한지였습니다. 이 글에서는 제가 겪은 실수들을 바탕으로, 여러분이 같은 시행착오를 겪지 않도록 실전 팁을 담았습니다.

1. 파일 찾기

특정 확장자 파일 찾기

pathlib.Path.glob**폴더 서랍을 열어 같은 확장자만 골라 담는 작업을 재귀적으로 해 줍니다. 예를 들어 프로젝트 전체에서 .pdf만 모을 때 수작업으로 찾기보다 훨씬 빠릅니다. 아래 코드는 python를 사용한 구현 예제입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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)

조건부 파일 찾기

다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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. 파일 이름 변경

일괄 이름 변경

아래 코드는 python를 사용한 구현 예제입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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_')

순번 추가

아래 코드는 python를 사용한 구현 예제입니다. 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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. 파일 정리

확장자별 폴더 정리

다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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. 자동 백업

백업 스크립트

다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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')

오래된 백업 삭제

아래 코드는 python를 사용한 구현 예제입니다. 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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. 중복 파일 찾기

해시 기반 중복 검사

다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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. 실전 예제

로그 파일 정리 스크립트

다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 함수를 통해 로직을 구현합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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처럼 원인이 다른 종류로 나누어 잡으면 디버깅이 빨라집니다. 다음은 python를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 에러 처리를 통해 안정성을 확보합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

# ✅ 안전한 파일 작업
# 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)

정리

핵심 요약

  1. 파일 찾기: glob, rglob
  2. 이름 변경: rename()
  3. 파일 이동: shutil.move()
  4. 백업: copytree(), make_archive()
  5. 중복 검사: 해시 비교

다음 단계


관련 글

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3