十个自动化日常任务的Python脚本

开发 前端
通过将这些脚本集成到工作流程中,可以提高生产力,节省时间,并减轻重复性任务的负担。尝试探索这些自动化脚本,了解Python如何让你的生活更轻松。

自动化是一种强大的方式,可以简化日常任务并节省时间。Python凭借其简单性和多功能性,是自动化日常生活各个方面的绝佳语言。在本文中,我们将探索10个实用的Python脚本,它们可以帮助自动化枯燥的任务,提高工作效率,让生活变得更加轻松。

1. 邮件自动化

描述:自动发送电子邮件、回复邮件或将收到的电子邮件分类到文件夹中。

脚本:

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

def send_email(subject, body, to_email):
    from_email = "your_email@gmail.com"
    password = "your_password"
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email, password)
    text = msg.as_string()
    server.sendmail(from_email, to_email, text)
    server.quit()
send_email("Test Subject", "This is a test email body.", "recipient_email@gmail.com")

2. 文件整理

描述:根据文件类型,将目录中的文件整理到相应的文件夹中。

脚本:

import os
import shutil

def organize_files(directory):
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            file_type = filename.split('.')[-1]
            target_dir = os.path.join(directory, file_type)
            if not os.path.exists(target_dir):
                os.makedirs(target_dir)
            shutil.move(os.path.join(directory, filename), os.path.join(target_dir, filename))
organize_files('/path/to/your/directory')

3. 每日新闻网页抓取

描述:从网站上抓取最新的新闻标题,并将其保存到文本文件中。

脚本:

import requests
from bs4 import BeautifulSoup

def scrape_news(url, output_file):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    headlines = soup.find_all('h2', class_='title')
    with open(output_file, 'w') as file:
        for headline in headlines:
            file.write(headline.text.strip() + '\n')
scrape_news('https://www.example-news-website.com', 'daily_news.txt')

4. 数据备份自动化

描述:将重要文件和目录备份到云存储服务,如Dropbox。

脚本:

import dropbox
import os

def backup_files(local_directory, dropbox_access_token, dropbox_directory):
    dbx = dropbox.Dropbox(dropbox_access_token)
    for root, dirs, files in os.walk(local_directory):
        for filename in files:
            local_path = os.path.join(root, filename)
            relative_path = os.path.relpath(local_path, local_directory)
            dropbox_path = os.path.join(dropbox_directory, relative_path)
            with open(local_path, 'rb') as f:
                dbx.files_upload(f.read(), dropbox_path, mode=dropbox.files.WriteMode.overwrite)
backup_files('/path/to/local/directory', 'your_dropbox_access_token', '/backup_directory')

5. 社交媒体自动化

描述:将更新发布到社交媒体平台,如Twitter。

脚本:

import tweepy

def post_tweet(api_key, api_key_secret, access_token, access_token_secret, message):
    auth = tweepy.OAuth1UserHandler(api_key, api_key_secret, access_token, access_token_secret)
    api = tweepy.API(auth)
    api.update_status(message)
post_tweet('api_key', 'api_key_secret', 'access_token', 'access_token_secret', 'Hello, Twitter!')

6. 日历事件创建器

描述:自动在Google日历中创建事件。

脚本:

from google.oauth2 import service_account
from googleapiclient.discovery import build

def create_event(calendar_id, summary, start_time, end_time):
    SCOPES = ['https://www.googleapis.com/auth/calendar']
    SERVICE_ACCOUNT_FILE = 'path/to/credentials.json'
    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = build('calendar', 'v3', credentials=credentials)
    event = {
        'summary': summary,
        'start': {'dateTime': start_time, 'timeZone': 'UTC'},
        'end': {'dateTime': end_time, 'timeZone': 'UTC'}
    }
    event = service.events().insert(calendarId=calendar_id, body=event).execute()
    print(f'Event created: {event.get("htmlLink")}')
create_event('your_calendar_id', 'Meeting', '2022-07-01T10:00:00Z', '2022-07-01T11:00:00Z')

7. 天气预报通知

描述:获取每日天气预报,并以电子邮件形式发送通知。

脚本:

import requests
import smtplib
from email.mime.text import MIMEText

def send_weather_forecast(api_key, city, email):
    weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
    response = requests.get(weather_url)
    weather_data = response.json()
    weather_description = weather_data['weather'][0]['description']
    temperature = weather_data['main']['temp'] - 273.15  # Convert Kelvin to Celsius
    message = f"Today's weather in {city}:\n{weather_description}\nTemperature: {temperature:.2f}°C"
    
    msg = MIMEText(message)
    msg['Subject'] = f"Weather Forecast for {city}"
    msg['From'] = "your_email@gmail.com"
    msg['To'] = email
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login("your_email@gmail.com", "your_password")
        server.send_message(msg)
send_weather_forecast('your_openweathermap_api_key', 'London', 'recipient_email@gmail.com')

8. 自动化财务交易

描述:自动管理和记录财务交易。

脚本:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

def record_transaction(spreadsheet_id, transaction_data):
    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
    credentials = ServiceAccountCredentials.from_json_keyfile_name('path/to/credentials.json', scope)
    client = gspread.authorize(credentials)
    sheet = client.open_by_key(spreadsheet_id).sheet1
    sheet.append_row(transaction_data)
record_transaction('your_spreadsheet_id', ['2022-07-01', 'Groceries', 50.00])

9. PDF操作

描述:将多个PDF文件合并为一个。

脚本:

import PyPDF2

def merge_pdfs(pdf_list, output_file):
    merger = PyPDF2.PdfFileMerger()
    for pdf in pdf_list:
        merger.append(pdf)
    merger.write(output_file)
    merger.close()
merge_pdfs(['file1.pdf', 'file2.pdf', 'file3.pdf'], 'merged.pdf')

10. 桌面通知

描述:发送桌面通知以提醒和警报。

脚本:

from plyer import notification

def send_notification(title, message):
    notification.notify(
        title=title,
        message=message,
        app_icnotallow=None,
        timeout=10,
    )
send_notification('Reminder', 'Time to take a break!')

总结

这些Python脚本展示了Python语言在自动化日常任务方面的多样性。通过将这些脚本集成到工作流程中,可以提高生产力,节省时间,并减轻重复性任务的负担。尝试探索这些自动化脚本,了解Python如何让你的生活更轻松。

责任编辑:武晓燕 来源: Python学研大本营
相关推荐

2024-07-01 18:07:30

Python脚本自动化

2022-10-09 14:50:44

Python脚本

2024-06-21 10:46:44

2024-10-28 19:36:05

2022-05-07 14:08:42

Python自动化脚本

2024-09-23 17:00:00

Python编程

2021-04-01 06:13:50

Ansible系统运维

2022-07-27 08:01:28

自动化DevOps

2024-08-19 10:21:37

接口Python魔法方法

2022-07-05 14:00:49

编排工具自动化

2022-01-11 06:53:23

脚本编码Python

2021-01-27 07:56:04

Python编程语言

2024-05-13 16:29:56

Python自动化

2024-08-16 21:14:36

2023-11-10 09:32:23

Python文件操作

2024-08-16 21:51:42

2022-02-17 13:03:28

Python脚本代码

2022-08-05 09:06:07

Python脚本代码

2022-02-24 14:55:32

人工智能IT技术

2024-06-12 12:36:48

CrontabPython
点赞
收藏

51CTO技术栈公众号