일상 업무를 자동화할 수 있는 21가지 간단한 Python 스크립트

프로그래밍 세계에서 10년 이상을 보낸 사람으로서, 반복적인 작업을 자동화하는 것이 상당한 시간과 노력을 절약할 수 있다는 것을 배웠습니다.

Python은 간단한 문법과 강력한 라이브러리를 통해 자동화 스크립트를 작성하기 위한 최고의 프로그래밍 언어 중 하나입니다. 프로그래머이든 일상적인 작업을 쉽게 만들고자 하는 사람이든, Python에는 도움이 될 수 있는 도구가 있습니다.

이 글에서는 다양한 작업을 자동화하기 위해 사용했던 21개의 Python 스크립트를 공유하겠습니다. 이 스크립트들은 업무 루틴에서 시간을 절약하고 효율성을 높이고자 하는 모든 사람에게 완벽합니다.

1. 파일 대량 이름 변경

파일 이름을 하나씩 변경하는 것은 시간이 많이 걸리는 작업일 수 있지만, Python의 os 모듈을 사용하여 이를 쉽게 자동화할 수 있습니다.

다음은 폴더 내 여러 파일의 이름을 주어진 패턴에 따라 변경하는 간단한 스크립트입니다:

import os

def bulk_rename(folder_path, old_name_part, new_name_part):
    for filename in os.listdir(folder_path):
        if old_name_part in filename:
            new_filename = filename.replace(old_name_part, new_name_part)
            os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))
            print(f"Renamed {filename} to {new_filename}")

folder = '/path/to/your/folder' bulk_rename(folder, 'old_part', 'new_part')

이 스크립트는 파일 이름에 old_name_part가 포함된 파일을 찾아 new_name_part로 대체합니다.

2. 파일 자동 백업

파일을 정기적으로 백업하는 것이 얼마나 중요한지는 모두 알고 있으며, 이 작업은 Python의 shutil 모듈을 사용하여 쉽게 자동화할 수 있습니다.

이 스크립트는 백업 목적으로 한 디렉토리에서 다른 디렉토리로 모든 파일을 복사합니다:

import shutil
import os

def backup_files(src_dir, dest_dir):
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    for file in os.listdir(src_dir):
        full_file_name = os.path.join(src_dir, file)
        if os.path.isfile(full_file_name):
            shutil.copy(full_file_name, dest_dir)
            print(f"Backed up {file} to {dest_dir}")

source = '/path/to/source/directory' destination = '/path/to/destination/directory' backup_files(source, destination)

이 스크립트를 매일 실행하도록 예약할 수 있습니다. cron (Linux) 또는 작업 스케줄러 (Windows)와 같은 작업 스케줄링 도구를 사용하십시오.

3. 인터넷에서 파일 다운로드

인터넷에서 파일을 자주 다운로드한다면, aiohttp 라이브러리를 사용하여이 작업을 자동화할 수 있습니다.

다음은 URL에서 파일을 다운로드하는 간단한 스크립트입니다.

import aiohttp
import asyncio
import aiofiles

async def download_file(url, filename):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            async with aiofiles.open(filename, 'wb') as file:
                await file.write(await response.read())
            print(f"Downloaded {filename}")

urls = {
    'https://example.com/file1.zip': 'file1.zip',
    'https://example.com/file2.zip': 'file2.zip'
}

async def download_all():
    tasks = [download_file(url, filename) for url, filename in urls.items()]
    await asyncio.gather(*tasks)

asyncio.run(download_all())

이 스크립트는 지정된 URL에서 파일을 다운로드하고 지정된 폴더에 저장합니다.

4. 이메일 보고서 자동화

정기적으로 이메일 보고서를 보내야하는 경우, smtplib 라이브러리를 사용하여 Gmail 계정에서 이메일을 쉽게 보낼 수 있습니다.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email):
    sender_email = '[email protected]'
    sender_password = 'yourpassword'
    receiver_email = to_email

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())
        server.quit()
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")

subject = 'Monthly Report'
body = 'Here is the monthly report.'
send_email(subject, body, '[email protected]')

이 스크립트는 제목과 본문이 포함 된 간단한 이메일을 지정된 수신자에게 보냅니다. 이 방법을 사용하는 경우 Gmail에서 보안 수준이 낮은 앱을 활성화해야합니다.

5. 작업 스케줄러 (작업 자동화)

특정 시간에 이메일을 보내거나 백업 스크립트를 실행하는 등의 작업을 자동화 할 수있는 schedule 라이브러리를 사용하여 작업을 쉽게 예약 할 수 있습니다.

import schedule
import time

def job():
    print("Running scheduled task!")

# Schedule the task to run every day at 10:00 AM
schedule.every().day.at("10:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

이 스크립트는 지정된 시간에 작업을 트리거하고 매일 오전 10시에 실행됩니다.

6. 데이터 수집을 위한 웹 스크레이핑

aiohttp를 동기 requests 라이브러리 대신 비동기 HTTP 요청에 사용하면 웹 스크래핑을 더 효율적으로 만들 수 있습니다.

이 예제는 병렬로 여러 페이지를 검색합니다.

import aiohttp
import asyncio
from bs4 import BeautifulSoup

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def scrape(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        html_pages = await asyncio.gather(*tasks)
        for html in html_pages:
            soup = BeautifulSoup(html, 'html.parser')
            print(soup.title.string)

urls = ['https://example.com/page1', 'https://example.com/page2'] asyncio.run(scrape(urls))

7. 소셜 미디어 게시물 자동화

소셜 미디어 계정을 관리한다면 Tweepy (Twitter용)와 Instagram-API (Instagram용)와 같은 라이브러리를 사용하여 게시물을 자동으로 올릴 수 있습니다.

아래는 Tweepy 라이브러리를 사용하여 트윗을 올리는 예시입니다:

import tweepy

def tweet(message):
    consumer_key = 'your_consumer_key'
    consumer_secret = 'your_consumer_secret'
    access_token = 'your_access_token'
    access_token_secret = 'your_access_token_secret'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)

    api.update_status(message)
    print("Tweet sent successfully!")

tweet("Hello, world!")

이 스크립트는 메시지 “Hello, world!“와 함께 트윗을 Twitter 계정에 올립니다.

8. 송장 생성 자동화

정기적으로 송장을 생성한다면 Fpdf와 같은 라이브러리를 사용하여 PDF 송장을 생성할 수 있습니다:

from fpdf import FPDF

def create_invoice(client_name, amount):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.cell(200, 10, txt="Invoice", ln=True, align='C')
    pdf.cell(200, 10, txt=f"Client: {client_name}", ln=True, align='L')
    pdf.cell(200, 10, txt=f"Amount: ${amount}", ln=True, align='L')
    pdf.output(f"{client_name}_invoice.pdf")
    print(f"Invoice for {client_name} created successfully!")

create_invoice('John Doe', 500)

이 스크립트는 간단한 송장을 생성하고 PDF로 저장합니다.

9. 웹사이트 가용성 모니터링

Python을 사용하여 웹사이트 가용성을 자동으로 모니터링할 수 있으며, 주기적으로 웹사이트가 온라인 상태인지 여부를 확인할 수 있는 requests 라이브러리를 사용할 수 있습니다:

import requests
import time

def check_website(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print(f"Website {url} is up!")
        else:
            print(f"Website {url} returned a status code {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"Error checking website {url}: {e}")

url = 'https://example.com' while True: check_website(url) time.sleep(3600) # Check every hour

이 스크립트는 웹사이트가 온라인 상태인지 확인하고 상태 코드를 출력합니다.

10. 이메일 자동 응답

자주 이메일을 받고 자동 응답을 설정하려면 imaplibsmtplib 라이브러리를 사용하여 자동으로 이메일에 회신할 수 있습니다:

import imaplib
import smtplib
from email.mime.text import MIMEText

def auto_reply():
    # Connect to email server
    mail = imaplib.IMAP4_SSL("imap.gmail.com")
    mail.login('[email protected]', 'yourpassword')
    mail.select('inbox')

    # Search for unread emails
    status, emails = mail.search(None, 'UNSEEN')

    if status == "OK":
        for email_id in emails[0].split():
            status, email_data = mail.fetch(email_id, '(RFC822)')
            email_msg = email_data[0][1].decode('utf-8')

            # Send auto-reply
            send_email("Auto-reply", "Thank you for your email. I'll get back to you soon.", '[email protected]')

def send_email(subject, body, to_email):
    sender_email = '[email protected]'
    sender_password = 'yourpassword'
    receiver_email = to_email

    msg = MIMEText(body)
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())

auto_reply()

이 스크립트는 미읽은 이메일에 미리 정의된 메시지로 자동으로 회신합니다.

11. 파일 정리

파이썬은 특히 파일 정리를 자동화하는 효과적인 방법을 제공하여, 조직적인 디렉토리를 유지하기 위해 오래된 파일을 삭제하거나 이동하는 데 도움이 됩니다.

아래는 ostime 모듈을 사용하여 지정된 일 수보다 오래된 파일을 삭제하는 간단한 스크립트입니다.

import aiofiles
import os
import asyncio
import time

async def clean_up(folder_path, days_old):
    now = time.time()
    cutoff_time = now - (days_old * 86400)
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.getmtime(file_path) < cutoff_time:
            await aiofiles.os.remove(file_path)
            print(f"Deleted {filename}")

folder = '/path/to/your/folder'
asyncio.run(clean_up(folder, 30))

12. 비밀번호 자동 생성

강력하고 고유한 비밀번호를 생성하는 것은 보안에 중요하며, 파이썬은 random 모듈을 사용하여 이 프로세스를 자동화하는 데 도움이 됩니다.

아래는 특정 길이의 무작위 비밀번호를 생성하여 보안을 강화하는 데 사용되는 문자, 숫자 및 특수 문자를 통합하는 간단한 스크립트입니다.

import random
import asyncio
import string

async def generate_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

async def generate_multiple_passwords(n, length=12):
    tasks = [generate_password(length) for _ in range(n)]
    passwords = await asyncio.gather(*tasks)
    print(passwords)

asyncio.run(generate_multiple_passwords(5))

13. 작업 추적기/알림

파이썬을 사용하여 작업 추적기 또는 알림 시스템을 만들 수 있으며, 이를 위해 datetimeasyncio 모듈을 사용할 수 있습니다.

import asyncio
from datetime import datetime

async def task_reminder(task_name, interval):
    while True:
        print(f"Reminder: {task_name} - {datetime.now()}")
        await asyncio.sleep(interval)

async def main():
    await asyncio.gather(
        task_reminder("Drink Water", 7200),  # Remind every 2 hours
        task_reminder("Take a Break", 3600)  # Remind every 1 hour
    )

asyncio.run(main())

이 스크립트는 예약된 시간에 작업에 대한 알림을 보냅니다.

14. 매일 보고서 자동 생성

데이터를 수집하고 보고서로 서식을 지정하기 위해 Python을 사용하여 매일 보고서를 자동화합니다:

import datetime
import aiofiles
import asyncio

async def generate_report(data):
    today = datetime.date.today()
    filename = f"daily_report_{today}.txt"
    async with aiofiles.open(filename, 'w') as file:
        await file.write(f"Report for {today}\n")
        await file.write("\n".join(data))
    print(f"Report generated: {filename}")

data = ["Task 1: Completed", "Task 2: Pending", "Task 3: Completed"]
asyncio.run(generate_report(data))

15. 시스템 리소스 모니터링

시스템 관리자라면 psutil 라이브러리를 사용하여 CPU 및 메모리 사용량과 같은 시스템 리소스를 모니터링하는 데 Python을 사용할 수 있습니다.

import psutil

def monitor_resources():
    cpu_usage = psutil.cpu_percent(interval=1)
    memory_usage = psutil.virtual_memory().percent
    print(f"CPU Usage: {cpu_usage}%")
    print(f"Memory Usage: {memory_usage}%")

monitor_resources()

16. 일괄 이미지 크기 조정

이미지를 일괄적으로 크기 조정해야 할 경우, Python은 Pillow 라이브러리를 사용하여 쉽게 처리할 수 있습니다.

from PIL import Image
import os
import asyncio
from concurrent.futures import ProcessPoolExecutor

def resize_image(filename, width, height):
    img = Image.open(filename)
    img = img.resize((width, height))
    img.save(f"resized_{filename}")
    return f"Resized {filename}"

async def resize_images(folder_path, width, height):
    with ProcessPoolExecutor() as executor:
        loop = asyncio.get_event_loop()
        tasks = []
        for filename in os.listdir(folder_path):
            if filename.endswith('.jpg'):
                tasks.append(loop.run_in_executor(
                    executor, resize_image, os.path.join(folder_path, filename), width, height))
        results = await asyncio.gather(*tasks)
        print(results)

folder = '/path/to/your/images'
asyncio.run(resize_images(folder, 800, 600))

이 스크립트는 폴더 내의 모든 .jpg 이미지를 지정된 크기로 조정합니다.

17. 클라우드로 데이터 백업 자동화

Python을 사용하여 Google Drive와 같은 클라우드 서비스에 백업을 자동화할 수 있습니다.

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

def backup_to_google_drive(file_path):
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    file = drive.CreateFile({'title': 'backup_file.txt'})
    file.Upload()
    print("Backup uploaded successfully!")

file = '/path/to/your/file.txt' backup_to_google_drive(file)

18. 매일 알림 만들기

매일 알림을 설정하는 것은 time 모듈을 사용하면 쉽게 할 수 있으며, 이는 2시간마다 물을 마시라는 알림을 제공합니다:

import time

def water_reminder():
    while True:
        print("Time to drink water!")
        time.sleep(7200)  # Remind every 2 hours

water_reminder()

19. Excel로 데이터 입력 자동화

자주 Excel에 데이터를 입력하는 경우, Pythonopenpyxl 라이브러리를 사용하여 이 작업을 자동화하는 데 도움을 줄 수 있습니다:

from openpyxl import Workbook

def create_excel(data):
    wb = Workbook()
    ws = wb.active
    for row in data:
        ws.append(row)
    wb.save('data.xlsx')
    print("Excel file created successfully!")

data = [
    ["Name", "Age", "City"],
    ["John", 30, "New York"],
    ["Anna", 25, "London"],
]
create_excel(data)

20. 데이터 정리 자동화

대규모 데이터 세트로 작업할 경우, Python은 CSV 파일에서 빈 행을 제거하는 데이터 정리 작업을 자동화할 수 있습니다:

import csv

def clean_csv(file_path):
    with open(file_path, 'r') as infile:
        reader = csv.reader(infile)
        rows = [row for row in reader if any(row)]
    
    with open(file_path, 'w', newline='') as outfile:
        writer = csv.writer(outfile)
        writer.writerows(rows)
    
    print("Empty rows removed from CSV")

file = '/path/to/your/data.csv' clean_csv(file)

21. 이미지에서 텍스트 추출

Python은 pytesseract 라이브러리를 사용하여 이미지에서 텍스트를 추출할 수 있으며, 이는 인쇄된 콘텐츠를 디지털화하거나 스캔한 문서에서 텍스트를 추출할 때 유용합니다.

from PIL import Image
import pytesseract

def extract_text_from_image(image_path):
    # Open the image file
    img = Image.open(image_path)
    
    # Use pytesseract to extract text
    text = pytesseract.image_to_string(img)
    
    return text

image_path = 'path_to_your_image.jpg'
extracted_text = extract_text_from_image(image_path)
print("Extracted Text:\n", extracted_text)
결론

이것은 Python이 일상적인 작업을 자동화하는 데 할 수 있는 몇 가지 예일 뿐입니다. 간결한 문법과 강력한 라이브러리를 갖춘 Python은 거의 모든 작업을 처리할 수 있습니다.

파일을 관리하거나 이메일을 보내거나 보고서를 생성하든, Python은 시간을 절약하고 생산성을 향상시킬 수 있습니다. 그러니 오늘부터 Python 자동화를 시작하고 일상적인 일을 처리하도록 하세요!

Source:
https://www.tecmint.com/python-automation-scripts/