Pythonで始める自動化スクリプト|日常業務を楽にする使い方10選







Pythonで始める自動化スクリプト|日常業務を楽にする使い方10選

Pythonで始める自動化スクリプト|日常業務を楽にする使い方10選

Pythonは初心者でも扱いやすいプログラミング言語であり、特に業務の自動化に非常に適しています。繰り返し行う作業や、無駄な手作業をPythonスクリプトで簡単に省力化することができます。

この記事では、「日常業務を効率化するPythonスクリプト10選」を具体的なコード例付きで紹介します。すぐに試せる実用的なものばかりなので、ぜひ参考にしてください。


1. フォルダ内ファイルを拡張子ごとに自動整理

ファイルが散らかったフォルダを、拡張子ごとに自動で仕分けして整理します。

import os
import shutil

def organize_by_extension(path):
    for file in os.listdir(path):
        filename, ext = os.path.splitext(file)
        ext = ext[1:] if ext else 'others'
        folder = os.path.join(path, ext)
        os.makedirs(folder, exist_ok=True)
        shutil.move(os.path.join(path, file), os.path.join(folder, file))

organize_by_extension('your/folder/path')

2. 毎日のバックアップスクリプト

指定フォルダの内容を定期的に別フォルダにコピーし、日付ごとに保存します。

import os
import shutil
from datetime import datetime

def backup_folder(src, dst):
    now = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_path = os.path.join(dst, f"backup_{now}")
    shutil.copytree(src, backup_path)

backup_folder('data', 'backup')

3. Excelファイルの読み込みと処理

Excelデータを読み込み、簡単な処理を加えて保存する例です。

import pandas as pd

df = pd.read_excel('sales.xlsx')
df['total'] = df['quantity'] * df['unit_price']
df.to_excel('sales_processed.xlsx', index=False)

4. Webページから情報を自動収集(スクレイピング)

ウェブサイトから記事のタイトルなどを取得するスクリプト。

import requests
from bs4 import BeautifulSoup

url = "https://example.com"
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
titles = soup.find_all("h2")
for title in titles:
    print(title.get_text())

5. 自動メール送信(Gmail利用)

SMTPを使ってPythonからメールを送信する簡易スクリプトです。

import smtplib
from email.mime.text import MIMEText

def send_mail(subject, body, to_email):
    from_email = "your@gmail.com"
    password = "your_password"
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
        smtp.login(from_email, password)
        smtp.send_message(msg)

send_mail("Test", "This is an automated email.", "receiver@example.com")

6. 定期実行のスケジューリング

毎朝9時にタスクを実行するようスケジューリングする例。

import schedule
import time

def task():
    print("Running daily task...")

schedule.every().day.at("09:00").do(task)

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

7. パスワード自動生成スクリプト

セキュアなパスワードを自動で生成します。

import random
import string

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

print(generate_password())

8. PDFの一括変換

テキストからPDFを自動生成します。

from fpdf import FPDF

def create_pdf(content, filename):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.multi_cell(0, 10, content)
    pdf.output(filename)

create_pdf("This is a test PDF created with Python.", "output.pdf")

9. システムのメモリ・CPU監視

psutilを使ってリアルタイムで使用状況をチェックします。

import psutil

print(f"CPU使用率: {psutil.cpu_percent()}%")
print(f"メモリ使用率: {psutil.virtual_memory().percent}%")

10. LINE通知ボット(LINE Notify)

LINE Notifyを使ってPythonからLINE通知を送る例です。

import requests

def send_line_notify(token, message):
    url = "https://notify-api.line.me/api/notify"
    headers = {"Authorization": f"Bearer {token}"}
    data = {"message": message}
    requests.post(url, headers=headers, data=data)

token = "YOUR_LINE_NOTIFY_TOKEN"
send_line_notify(token, "PythonからLINE通知を送信しました。")

まとめ

日々の業務の中には、繰り返しの作業や時間のかかる処理が多くあります。Pythonの自動化スクリプトを使うことで、作業時間を削減し、ミスを防ぎ、効率的に業務を進めることが可能です。

まずは、1つでも気になるスクリプトを動かしてみましょう。少しずつ慣れていくことで、自分だけの便利な自動化ツールを作れるようになります。


コメント

タイトルとURLをコピーしました