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)或任务计划程序(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

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可以通过像Google Drive这样的云服务自动备份,可以使用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中,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/