日常のタスクを自動化する21のシンプルなPythonスクリプト

プログラミングの世界で10年以上を過ごしてきた私は、繰り返し作業を自動化することが時間と労力を節約できることを学びました。

Pythonは、シンプルな構文と強力なライブラリを備えており、自動化スクリプトを作成するための最適なプログラミング言語の1つです。プログラマーであるか、日常のタスクを簡単にしたい人にとって、Pythonは役立つツールを提供しています。

この記事では、さまざまなタスクを自動化するために使用した21のPythonスクリプトを共有します。これらのスクリプトは、作業ルーチンで時間を節約し効率を向上させたい人に最適です。

1. 一括ファイル名変更

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モジュールを使用することでこのタスクを簡単に自動化できます。

このスクリプトは、バックアップ目的で1つのディレクトリから別のディレクトリにすべてのファイルをコピーします:

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リクエストを行うと、Webスクレイピングをより効率的に行えます。

この例では複数のページを並行して取得します。

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. ファイルのクリーンアップ

Pythonは、ファイルの整理を自動化する効果的な方法を提供しており、特に整理されたディレクトリを維持するために古いファイルを削除または移動する際に便利です。

以下は、osおよびtimeモジュールを使用して、指定された日数よりも古いファイルを削除する単純なスクリプトです。

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. パスワードの自動生成

強力で一意なパスワードの作成はセキュリティ上重要ですが、Pythonを使用して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. タスクトラッカー/リマインダー

Pythonを使用してタスクトラッカーやリマインダーシステムを作成することは、datetimeおよびasyncioモジュールを使用することで実現できます。

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.クラウドへのデータバックアップの自動化

Google DriveなどのクラウドサービスへのバックアップをPythonを使用して自動化することができます。その際にはpydriveなどのライブラリが活用されます。

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に頻繁にデータを入力する場合、ExcelPythonを使用してこのタスクを自動化するのにopenpyxlライブラリが役立ちます。

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/