⑦Pythonプログラミング

実践!Pythonで自動化スクリプトを作る【ファイル整理・スクレイピング】

⑦Pythonプログラミング
記事内に広告が含まれています。

Pythonで実際に使える自動化スクリプトを作ります。ファイル整理・Webスクレイピング・メール送信など実践的な例を解説します。

ファイル整理自動化

from pathlib import Path
import shutil
from datetime import datetime

def organize_downloads(download_dir):
    """ダウンロードフォルダを拡張子ごとに整理"""
    categories = {
        "画像": [".jpg", ".jpeg", ".png", ".gif", ".webp"],
        "動画": [".mp4", ".mov", ".avi", ".mkv"],
        "文書": [".pdf", ".docx", ".xlsx", ".txt"],
        "圧縮": [".zip", ".tar", ".gz"],
    }
    p = Path(download_dir)
    for file in p.iterdir():
        if not file.is_file():
            continue
        for category, exts in categories.items():
            if file.suffix.lower() in exts:
                dest = p / category
                dest.mkdir(exist_ok=True)
                shutil.move(str(file), dest / file.name)
                print(f"移動: {file.name} → {category}/")
                break

organize_downloads("/home/user/Downloads")

WebスクレイピングでデータをCSVに保存

pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
import csv

def scrape_news(url):
    headers = {"User-Agent": "Mozilla/5.0"}
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, "html.parser")
    articles = []
    for h2 in soup.find_all("h2")[:10]:
        articles.append({"title": h2.text.strip()})
    with open("news.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["title"])
        writer.writeheader()
        writer.writerows(articles)
    print(f"{len(articles)}件保存しました")

まとめ

  • pathlibとshutilでファイル整理を自動化できる
  • requests + BeautifulSoupでWebスクレイピングができる
  • スクレイピングはサイトの利用規約を必ず確認してから行う

コメント

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