首页 > 后端开发 > Python教程 > 自动执行日常任务的 Python 脚本

自动执行日常任务的 Python 脚本

Mary-Kate Olsen
发布: 2024-11-29 14:02:11
原创
658 人浏览过

Python Scripts to Automate Your Daily Tasks

每个人都必须拥有的收藏......

Python 凭借其简单性和强大的库改变了我们实现自动化的方式。无论您是技术爱好者、忙碌的专业人士,还是只是想简化日常工作,Python 都可以帮助您自动执行重复性任务,节省时间并提高效率。这里收集了 10 个基本的 Python 脚本,可以帮助您自动化日常生活的各个方面。

让我们开始吧!


1.自动发送电子邮件

手动发送电子邮件,尤其是重复发送的电子邮件,可能非常耗时。使用 Python 的 smtplib 库,您可以轻松地自动化此过程。无论是发送提醒、更新还是个性化消息,这个脚本都可以处理。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(receiver_email, subject, body):
    sender_email = "your_email@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
            print("Email sent successfully!")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
send_email("receiver_email@example.com", "Subject Here", "Email body goes here.")

登录后复制
登录后复制

此脚本可以轻松集成到更大的工作流程中,例如发送报告或警报。

2.文件管理器

如果您的下载文件夹一片混乱,那么这个脚本适合您。它按扩展名组织文件,将它们整齐地放入子文件夹中。不再需要筛选数十个文件来找到您需要的内容!

import os
from shutil import move

def organize_folder(folder_path):
    for file in os.listdir(folder_path):
        if os.path.isfile(os.path.join(folder_path, file)):
            ext = file.split('.')[-1]
            ext_folder = os.path.join(folder_path, ext)
            os.makedirs(ext_folder, exist_ok=True)
            move(os.path.join(folder_path, file), os.path.join(ext_folder, file))

# Example usage
organize_folder("C:/Users/YourName/Downloads")

登录后复制
登录后复制

此脚本对于管理 PDF、图像或文档等文件特别有用。

3.网页抓取新闻头条

通过从您最喜爱的网站抓取头条新闻来了解最新新闻。 Python 的“requests”和“BeautifulSoup”库使这个过程变得无缝。

import requests
from bs4 import BeautifulSoup

def fetch_headlines(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    headlines = [h.text for h in soup.find_all('h2', class_='headline')]
    return headlines

# Example usage
headlines = fetch_headlines("https://news.ycombinator.com/")
print("\n".join(headlines))

登录后复制
登录后复制

无论您是新闻迷还是需要工作更新,此脚本都可以安排每天运行。

4.每日天气通知

从天气更新开始新的一天!此脚本使用 OpenWeatherMap API 获取您所在城市的天气数据并显示温度和天气预报。

import requests

def get_weather(city):
    api_key = "your_api_key"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url).json()
    if response.get("main"):
        temp = response['main']['temp']
        weather = response['weather'][0]['description']
        print(f"The current weather in {city} is {temp}°C with {weather}.")
    else:
        print("City not found!")

# Example usage
get_weather("New York")

登录后复制

只需稍加调整,您就可以让它直接向您的手机发送通知。

5.自动化社交媒体帖子

使用 Python 安排社交媒体帖子变得轻而易举。使用“tweepy”库以编程方式发布推文。

import tweepy

def post_tweet(api_key, api_key_secret, access_token, access_token_secret, tweet):
    auth = tweepy.OAuthHandler(api_key, api_key_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    api.update_status(tweet)
    print("Tweet posted!")

# Example usage
post_tweet("api_key", "api_key_secret", "access_token", "access_token_secret", "Hello, Twitter!")

登录后复制

非常适合想要提前计划帖子的社交媒体管理者和内容创建者。

6.PDF 到文本转换

手动从 PDF 中提取文本非常繁琐。该脚本使用“PyPDF2”库简化了流程。

from PyPDF2 import PdfReader

def pdf_to_text(file_path):
    reader = PdfReader(file_path)
    text = ""
    for page in reader.pages:
        text += page.extract_text()
    return text

# Example usage
print(pdf_to_text("sample.pdf"))

登录后复制

非常适合归档或分析文本较多的文档。

7.使用 CSV 进行费用跟踪

通过将费用记录到 CSV 文件中来跟踪您的费用。此脚本可帮助您维护数字记录,以便稍后分析。

import csv

def log_expense(file_name, date, item, amount):
    with open(file_name, mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([date, item, amount])
        print("Expense logged!")

# Example usage
log_expense("expenses.csv", "2024-11-22", "Coffee", 4.5)

登录后复制

将其变成一种习惯,您就会清楚地了解自己的消费模式。

8.自动化桌面通知

您的计算机上需要提醒或警报吗?该脚本使用“plyer”库发送桌面通知。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(receiver_email, subject, body):
    sender_email = "your_email@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
            print("Email sent successfully!")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
send_email("receiver_email@example.com", "Subject Here", "Email body goes here.")

登录后复制
登录后复制

非常适合任务管理和事件提醒。

9.网站可用性检查

使用这个简单的脚本监控您的网站或喜爱的平台的正常运行时间。

import os
from shutil import move

def organize_folder(folder_path):
    for file in os.listdir(folder_path):
        if os.path.isfile(os.path.join(folder_path, file)):
            ext = file.split('.')[-1]
            ext_folder = os.path.join(folder_path, ext)
            os.makedirs(ext_folder, exist_ok=True)
            move(os.path.join(folder_path, file), os.path.join(ext_folder, file))

# Example usage
organize_folder("C:/Users/YourName/Downloads")

登录后复制
登录后复制

对网络开发人员和企业主有用。

10.自动化数据备份

再也不用担心丢失重要文件了。该脚本自动将文件备份到指定位置。

import requests
from bs4 import BeautifulSoup

def fetch_headlines(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    headlines = [h.text for h in soup.find_all('h2', class_='headline')]
    return headlines

# Example usage
headlines = fetch_headlines("https://news.ycombinator.com/")
print("\n".join(headlines))

登录后复制
登录后复制

每周或每天运行一次,以确保您的数据始终安全。


这 10 个脚本演示了 Python 如何处理重复性任务并简化您的日常生活。从管理文件到在社交媒体上发布,自动化开启了无限的可能性。选择一个脚本,对其进行自定义,并将其集成到您的工作流程中。很快,您就会想知道如果没有 Python 自动化,您是如何生活的!

你会先尝试哪一个?

请在评论部分告诉我们!

以上是自动执行日常任务的 Python 脚本的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板