21個簡單的Python腳本,可以自動化您的日常任務

作為在編程界度過十多年的人,我已經了解到自動化重複任務可以節省大量時間和精力。

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)或 Task Scheduler(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:00 AM

6. 網頁抓取用於數據收集

使用 aiohttp 進行非同步 HTTP 請求,而不是同步的 requests 庫,可以使網頁爬蟲更有效率。

這個例子可以同時檢索多個網頁。

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!")

這個腳本會在你的 Twitter 帳戶發送一條帶有消息 “Hello, world!” 的推文。

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 提供了一種有效的方法來自動執行文件清理,特別是刪除或移動舊文件以保持目錄的整潔。

以下是一個使用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. 自動生成密碼

創建強大、唯一的密碼對於安全至關重要,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. 任務追蹤/提醒

使用datetimeasyncio模塊可以實現在 Python 中創建任務追蹤或提醒系統。

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. 監控系統資源

如果您是系統管理員,您可以使用 Python 監控系統的資源,如CPU 和內存使用,借助psutil庫的幫助。

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可以通過庫(如pydrive)實現自動備份到雲端服務(如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中輸入數據,Python可以通過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/