파일 자동화
Python을 사용하면 반복적인 파일 작업을 자동화할 수 있습니다. 파일과 폴더를 생성, 삭제, 이동, 복사하는 작업을 코드로 처리해보겠습니다.
핵심 모듈
os 모듈
운영체제와 상호작용하는 기본 모듈입니다.
import os
# 현재 작업 디렉토리 확인
current_dir = os.getcwd()
print(f"현재 디렉토리: {current_dir}")
# 디렉토리 변경
os.chdir('/Users/username/Documents')
# 디렉토리 목록 보기
files = os.listdir('.')
print(files)
# 경로 결합 (운영체제에 맞게 자동으로)
path = os.path.join('folder', 'subfolder', 'file.txt')
print(path) # folder/subfolder/file.txt (macOS/Linux)
shutil 모듈
고수준 파일 작업을 위한 모듈입니다.
import shutil
# 파일 복사
shutil.copy('source.txt', 'destination.txt')
# 메타데이터 포함 복사
shutil.copy2('source.txt', 'destination.txt')
# 폴더 전체 복사
shutil.copytree('source_folder', 'destination_folder')
# 파일/폴더 이동
shutil.move('old_location.txt', 'new_location.txt')
# 폴더 삭제 (내용물 포함)
shutil.rmtree('folder_to_delete')
폴더 및 파일 생성
디렉토리 생성
import os
# 단일 디렉토리 생성
if not os.path.exists('new_folder'):
os.mkdir('new_folder')
# 중첩 디렉토리 생성
os.makedirs('parent/child/grandchild', exist_ok=True)
# exist_ok=True: 이미 존재해도 에러 발생 안 함
파일 생성
# 빈 파일 생성
with open('new_file.txt', 'w') as f:
pass
# 내용과 함께 파일 생성
with open('data.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!\n')
f.write('Python 자동화')
파일 및 폴더 삭제
import os
import shutil
# 파일 삭제
if os.path.exists('file_to_delete.txt'):
os.remove('file_to_delete.txt')
# 빈 디렉토리 삭제
if os.path.exists('empty_folder'):
os.rmdir('empty_folder')
# 내용이 있는 디렉토리 삭제
if os.path.exists('folder_with_files'):
shutil.rmtree('folder_with_files')
파일 검색
os.walk로 하위 폴더 탐색
import os
# 모든 하위 폴더의 파일 찾기
for root, dirs, files in os.walk('/path/to/search'):
for file in files:
if file.endswith('.txt'):
full_path = os.path.join(root, file)
print(full_path)
glob 패턴 매칭
import glob
# 현재 폴더의 모든 .py 파일
python_files = glob.glob('*.py')
# 모든 하위 폴더의 .txt 파일
all_txt_files = glob.glob('**/*.txt', recursive=True)
# 특정 패턴의 파일
data_files = glob.glob('data_*.csv')
# pathlib과 함께 사용
from pathlib import Path
for file in Path('.').rglob('*.log'):
print(file)
파일 정보 확인
import os
from datetime import datetime
file_path = 'example.txt'
# 파일 존재 확인
exists = os.path.exists(file_path)
# 파일인지 디렉토리인지 확인
is_file = os.path.isfile(file_path)
is_dir = os.path.isdir(file_path)
# 파일 크기 (바이트)
size = os.path.getsize(file_path)
print(f"크기: {size / 1024:.2f} KB")
# 파일 수정 시간
mtime = os.path.getmtime(file_path)
modified_date = datetime.fromtimestamp(mtime)
print(f"마지막 수정: {modified_date}")
# 파일 생성 시간
ctime = os.path.getctime(file_path)
created_date = datetime.fromtimestamp(ctime)
print(f"생성 시간: {created_date}")
실전 예제
1. 사진 정리 스크립트
날짜별로 사진을 자동으로 분류합니다.
import os
import shutil
from datetime import datetime
from pathlib import Path
def organize_photos(source_dir, dest_dir):
"""사진을 날짜별로 정리"""
# 목적지 폴더 생성
os.makedirs(dest_dir, exist_ok=True)
# 이미지 확장자
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.heic'}
for file_path in Path(source_dir).rglob('*'):
if file_path.suffix.lower() in image_extensions:
# 파일 수정 날짜 가져오기
mtime = os.path.getmtime(file_path)
date = datetime.fromtimestamp(mtime)
# 연도/월 폴더 생성
year_month = date.strftime('%Y/%m')
target_dir = os.path.join(dest_dir, year_month)
os.makedirs(target_dir, exist_ok=True)
# 파일 이동
target_path = os.path.join(target_dir, file_path.name)
# 중복 파일명 처리
counter = 1
while os.path.exists(target_path):
name, ext = os.path.splitext(file_path.name)
target_path = os.path.join(
target_dir,
f"{name}_{counter}{ext}"
)
counter += 1
shutil.move(str(file_path), target_path)
print(f"이동: {file_path.name} -> {year_month}/")
# 사용 예제
organize_photos('/Users/username/Downloads', '/Users/username/Photos')