매일 반복되는 귀찮은 작업들, Python으로 자동화할 수 있습니다. 제가 실제로 사용하는 스크립트들을 공유합니다.
1. 엑셀 파일 자동 처리
여러 엑셀 파일을 합치고, 필터링하고, 요약하는 작업을 자동화했습니다.
import pandas as pd
from pathlib import Path
def merge_excel_files(folder_path, output_file):
"""폴더 내 모든 엑셀 파일을 하나로 합치기"""
all_files = Path(folder_path).glob('*.xlsx')
df_list = []
for file in all_files:
df = pd.read_excel(file)
df['source_file'] = file.name
df_list.append(df)
# 모두 합치기
merged_df = pd.concat(df_list, ignore_index=True)
# 저장
merged_df.to_excel(output_file, index=False)
print(f"완료! {len(df_list)}개 파일을 합쳤습니다.")
# 사용 예시
merge_excel_files('./reports', 'merged_report.xlsx')2. 이메일 자동 발송
매주 월요일 아침마다 보내는 주간 리포트를 자동화했습니다.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_weekly_report(to_email, subject, body, attachment_path):
"""주간 리포트 자동 발송"""
# Gmail 설정
from_email = "your_email@gmail.com"
password = "your_app_password" # 앱 비밀번호 사용
# 이메일 구성
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
# 본문 추가
msg.attach(MIMEText(body, 'html'))
# 첨부파일 추가
with open(attachment_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
f'attachment; filename={attachment_path}')
msg.attach(part)
# 발송
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login(from_email, password)
server.send_message(msg)
print("이메일 발송 완료!")
# cron으로 매주 월요일 9시에 실행
# 0 9 * * 1 python send_report.py3. 파일 정리 자동화
다운로드 폴더를 파일 종류별로 자동 정리합니다.
import os
import shutil
from pathlib import Path
def organize_downloads(download_folder):
"""파일 종류별로 자동 정리"""
# 파일 타입별 폴더 매핑
file_types = {
'Images': ['.jpg', '.jpeg', '.png', '.gif', '.svg'],
'Documents': ['.pdf', '.doc', '.docx', '.txt', '.xlsx'],
'Videos': ['.mp4', '.avi', '.mov', '.mkv'],
'Archives': ['.zip', '.rar', '.7z', '.tar'],
'Code': ['.py', '.js', '.html', '.css', '.json'],
}
download_path = Path(download_folder)
for file in download_path.iterdir():
if file.is_file():
file_ext = file.suffix.lower()
# 파일 타입 찾기
for folder, extensions in file_types.items():
if file_ext in extensions:
# 대상 폴더 생성
dest_folder = download_path / folder
dest_folder.mkdir(exist_ok=True)
# 파일 이동
shutil.move(str(file), str(dest_folder / file.name))
print(f"{file.name} → {folder}/")
break
# 매일 자동 실행
organize_downloads(os.path.expanduser('~/Downloads'))4. 웹사이트 모니터링
특정 웹사이트의 변경사항을 감지하고 알림을 보냅니다.
import requests
from bs4 import BeautifulSoup
import hashlib
import time
def monitor_website(url, check_interval=3600):
"""웹사이트 변경 감지"""
previous_hash = None
while True:
try:
# 웹페이지 가져오기
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 특정 부분만 추출 (예: 제목과 본문)
content = soup.find('article')
if content:
content_text = content.get_text()
# 해시값 계산
current_hash = hashlib.md5(
content_text.encode()
).hexdigest()
# 변경 감지
if previous_hash and current_hash != previous_hash:
print(f"🚨 변경 감지! {url}")
# 여기에 알림 로직 추가 (슬랙, 이메일 등)
previous_hash = current_hash
# 대기
time.sleep(check_interval)
except Exception as e:
print(f"오류: {e}")
time.sleep(60)
# 사용 예시
monitor_website('https://example.com/news', check_interval=1800)5. 스크린샷 자동 촬영
정해진 시간에 화면을 캡처하여 저장합니다. (근태 관리 등)
from PIL import ImageGrab
from datetime import datetime
import os
def take_screenshot(save_folder='screenshots'):
"""화면 캡처 및 저장"""
# 폴더 생성
os.makedirs(save_folder, exist_ok=True)
# 스크린샷
screenshot = ImageGrab.grab()
# 파일명 (날짜_시간)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f"{save_folder}/screenshot_{timestamp}.png"
# 저장
screenshot.save(filename)
print(f"스크린샷 저장: {filename}")
# 30분마다 실행
import schedule
schedule.every(30).minutes.do(take_screenshot)
while True:
schedule.run_pending()
time.sleep(60)6. CSV to JSON 변환기
API 테스트용으로 CSV 데이터를 JSON으로 빠르게 변환합니다.
import csv
import json
def csv_to_json(csv_file, json_file):
"""CSV를 JSON으로 변환"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
csv_reader = csv.DictReader(f)
for row in csv_reader:
data.append(row)
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f"변환 완료: {len(data)}개 레코드")
# 사용
csv_to_json('data.csv', 'data.json')7. 이미지 일괄 리사이즈
블로그 업로드용 이미지를 일괄 리사이즈합니다.
from PIL import Image
from pathlib import Path
def resize_images(folder, max_width=1200):
"""이미지 일괄 리사이즈"""
folder_path = Path(folder)
output_folder = folder_path / 'resized'
output_folder.mkdir(exist_ok=True)
for img_file in folder_path.glob('*.{jpg,jpeg,png}'):
try:
img = Image.open(img_file)
# 비율 유지하며 리사이즈
if img.width > max_width:
ratio = max_width / img.width
new_height = int(img.height * ratio)
img = img.resize((max_width, new_height),
Image.Resampling.LANCZOS)
# 저장
output_path = output_folder / img_file.name
img.save(output_path, quality=85, optimize=True)
print(f"✓ {img_file.name}")
except Exception as e:
print(f"✗ {img_file.name}: {e}")
resize_images('./images')8. 슬랙 알림 봇
중요한 작업 완료 시 슬랙으로 알림을 보냅니다.
import requests
def send_slack_message(webhook_url, message):
"""슬랙으로 메시지 발송"""
payload = {
'text': message,
'username': '자동화 봇',
'icon_emoji': ':robot_face:'
}
response = requests.post(webhook_url, json=payload)
if response.status_code == 200:
print("슬랙 알림 전송 완료")
else:
print(f"전송 실패: {response.status_code}")
# 사용 예시
webhook = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
# 작업 완료 후
send_slack_message(webhook, "✅ 데이터 처리 완료!")실전 활용 팁
1. 스케줄링
자동 실행을 위해 다음 도구들을 활용하세요:
- Windows: 작업 스케줄러
- Mac/Linux: cron
- Python: schedule 라이브러리
2. 오류 처리
자동화 스크립트는 항상 예외 처리를 해야 합니다:
try:
# 작업 수행
process_data()
except Exception as e:
# 로그 기록
with open('error.log', 'a') as f:
f.write(f"{datetime.now()}: {e}\n")
# 알림 발송
send_slack_message(webhook, f"⚠️ 오류 발생: {e}")시간 절약 효과
이런 스크립트들로 절약한 시간:
- 엑셀 처리: 하루 30분 → 1분
- 파일 정리: 주 1시간 → 자동
- 리포트 발송: 주 2시간 → 자동
월 평균 20시간 절약!
마무리
작은 자동화부터 시작하세요. "이거 매번 반복하네?"라는 생각이 들면 자동화할 타이밍입니다.