20 个简单的 Python 脚本可自动执行您的日常任务

作为在编程领域工作了十多年的人,我了解到自动化重复性任务可以节省大量的时间和精力。

Python凭借其简单的语法和强大的库,是创建自动化脚本的最佳编程语言之一。无论您是程序员还是希望使日常任务变得更轻松的人,Python有可以帮助您的工具。

在本文中,我将分享 20 个用于自动执行各种任务的 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)

您可以使用任务计划工具(例如(Linux)或任务调度程序(视窗)。

3. 从互联网下载文件

如果你经常,那么您可以使用自动执行此任务requests图书馆。

下面是一个从 URL 下载文件的简单脚本:

import requests

def download_file(url, destination_folder):
    response = requests.get(url)
    if response.status_code == 200:
        with open(destination_folder, 'wb') as file:
            file.write(response.content)
        print(f"Downloaded {url} to {destination_folder}")
    else:
        print(f"Failed to download {url}")

url = 'https://example.com/file.pdf' destination = '/path/to/destination/file.pdf' download_file(url, destination)

该脚本从指定的 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 = '' 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, '')

该脚本将向指定收件人发送一封带有主题和正文的简单电子邮件。如果您使用此方法,请确保在 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. 用于数据收集的网页抓取

网页抓取是一种强大的技术,可以自动从网站收集数据,Python 的BeautifulSouprequests库使这个过程变得简单。

import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data = soup.find_all('h1')  # Example: Get all headings
    for item in data:
        print(item.text)

url = 'https://example.com' scrape_website(url)

该脚本从网页中获取内容并打印出所有标题(h1标签)。您可以调整它以抓取其他类型的数据。

7.自动化社交媒体帖子

如果您管理社交媒体帐户,那么您可以使用以下库自动发布内容Tweepy(推特)和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('', '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.", '') def send_email(subject, body, to_email): sender_email = '' 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 os
import time

def clean_up(folder_path, days_old):
    now = time.time()
    cutoff_time = now - (days_old * 86400)  # 86400 seconds in a day
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.getmtime(file_path) < cutoff_time:
            os.remove(file_path)
            print(f"Deleted {filename}")

folder = '/path/to/your/folder' clean_up(folder, 30) # Delete files older than 30 days

12.自动生成密码

创建强而独特的密码对于安全至关重要,Python 可以使用以下方法帮助自动化此过程:random模块。

下面是一个简单的脚本,它生成指定长度的随机密码,包含字母、数字和特殊字符以增强安全性。

import random
import string

def generate_password(length=12):
    # Define the character set: letters, digits, and punctuation
    characters = string.ascii_letters + string.digits + string.punctuation
    
    # Generate a random password
    password = ''.join(random.choice(characters) for _ in range(length))
    
    return password

# Example usage: generate a password of 16 characters
password_length = 16
random_password = generate_password(password_length)
print(f"Generated Password: {random_password}")

13. 任务跟踪器/提醒

在 Python 中创建任务跟踪器或提醒系统可以使用datetimeschedule模块。

import schedule
import time
from datetime import datetime

def task_reminder(task_name):
    print(f"Reminder: {task_name} - {datetime.now()}")

schedule.every().day.at("09:00").do(task_reminder, task_name="Morning Meeting")

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

该脚本在预定时间发送有关任务的提醒。

14.自动生成每日报告

通过使用 Python 收集数据并将其格式化为报告来自动生成每日报告:

import datetime

def generate_report(data):
    today = datetime.date.today()
    filename = f"daily_report_{today}.txt"
    with open(filename, 'w') as file:
        file.write(f"Report for {today}\n")
        file.write("\n".join(data))
    print(f"Report generated: {filename}")

data = ["Task 1: Completed", "Task 2: Pending", "Task 3: Completed"]
generate_report(data)

15. 监控系统资源

如果您是系统管理员,您可以使用 Python 来监控系统资源,例如,在帮助下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

def resize_images(folder_path, width, height):
    for filename in os.listdir(folder_path):
        if filename.endswith('.jpg'):
            img = Image.open(os.path.join(folder_path, filename))
            img = img.resize((width, height))
            img.save(os.path.join(folder_path, f"resized_{filename}"))
            print(f"Resized {filename}")

folder = '/path/to/your/images' resize_images(folder, 800, 600)

该脚本调整了所有.jpg将文件夹中的图像调整为指定尺寸。

17. 自动将数据备份到云端

自动备份到云服务,例如谷歌云端硬盘使用 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,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)

如果您使用大型数据集,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)
结论

这些只是 Python 可以自动执行日常任务的几个示例。凭借其简单的语法和强大的库,Python 几乎可以处理您交给它的任何任务。

无论您是管理文件、发送电子邮件还是生成报告,Python 都可以节省您的时间并提高您的工作效率。所以,今天就开始使用 Python 自动化,让它处理你的日常琐事吧!