21个Python脚本自动执行日常任务(2)

简介: 21个Python脚本自动执行日常任务(2)

引言

作为编程领域摸爬滚打超过十年的老手,我深刻体会到,自动化那些重复性工作能大大节省我们的时间和精力。

Python以其简洁的语法和功能强大的库支持,成为了编写自动化脚本的首选语言。无论你是专业的程序员,还是希望简化日常工作的普通人,Python都能提供你需要的工具。

本文将介绍我实际使用过的21个Python脚本,它们能帮助你自动化各种任务,特别适合那些希望在工作中节省时间、提升效率的朋友。

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. 任务追踪与提醒工具

利用 Python 的 datetimeasyncio 模块,可以开发出任务追踪或提醒系统。

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 和 psutil 库来监控系统的资源使用情况,例如 CPU 和内存。

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 模块,可以轻松设定每日提醒,比如每两小时提醒你喝水:

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 进行自动化,让它成为你处理日常杂务的得力助手!

相关文章
|
2月前
|
供应链 并行计算 算法
1行Python搞定高频任务!26个实用技巧解决日常+进阶需求
本文整理了26个Python极简技巧,涵盖日常高频操作与进阶玩法,助你用最少代码高效解决问题,提升编程效率。适合各阶段Python学习者参考。
99 27
|
3月前
|
JSON 算法 API
深度分析小红书城API接口,用Python脚本实现
小红书作为以UGC内容为核心的生活方式平台,其非官方API主要通过移动端抓包解析获得,涵盖内容推荐、搜索、笔记详情、用户信息和互动操作等功能。本文分析了其接口体系、认证机制及请求规范,并提供基于Python的调用框架,涉及签名生成、登录态管理与数据解析。需注意非官方接口存在稳定性与合规风险,使用时应遵守平台协议及法律法规。
|
3月前
|
JSON API 数据安全/隐私保护
【干货满满】分享微店API接口到手价,用python脚本实现
微店作为知名社交电商平台,其开放平台提供商品查询、订单管理等API接口。本文介绍如何通过微店API获取商品到手价(含优惠、券等),涵盖认证机制、Python实现及关键说明。
|
3月前
|
JSON API 数据安全/隐私保护
【干货满满】分享淘宝API接口到手价,用python脚本实现
淘宝开放平台通过API可获取商品到手价,结合商品详情与联盟接口实现优惠计算。需使用AppKey、AppSecret及会话密钥认证,调用taobao.tbk.item.info.get接口获取最终价格。代码示例展示签名生成与数据解析流程。
|
3月前
|
JSON API 数据格式
深度分析大麦网API接口,用Python脚本实现
大麦网为国内领先演出票务平台,提供演唱会、话剧、体育赛事等票务服务。本文基于抓包分析其非官方接口,并提供Python调用方案,涵盖演出列表查询、详情获取及城市列表获取。需注意非官方接口存在稳定性风险,使用时应遵守平台规则,控制请求频率,防范封禁与法律风险。适用于个人学习、演出信息监控等场景。
|
3月前
|
JSON API 开发者
深度分析阿里妈妈API接口,用Python脚本实现
阿里妈妈是阿里巴巴旗下营销平台,提供淘宝联盟、直通车等服务,支持推广位管理、商品查询等API功能。本文详解其API调用方法,重点实现商品推广信息(佣金、优惠券)获取,并提供Python实现方案。
|
3月前
|
JSON API 数据安全/隐私保护
深度分析虾皮城API接口,用Python脚本实现
虾皮开放平台提供丰富的API接口,支持商品管理、订单处理及促销信息查询等功能。本文详解API认证机制与调用方法,基于Python实现商品价格及到手价获取方案,适用于电商数据分析与运营。
|
3月前
|
JSON API 数据安全/隐私保护
【干货满满】分享拼多多API接口到手价,用python脚本实现
拼多多开放平台提供商品价格查询API,通过“pdd.ddk.goods.detail”接口可获取商品基础价、优惠券、拼团价等信息。结合client_id、client_secret及签名机制实现身份认证,支持推广位ID获取专属优惠。本文提供完整Python实现,涵盖签名生成、接口调用与价格解析逻辑,适用于比价工具、导购平台等场景。
|
3月前
|
API 数据安全/隐私保护 开发者
深度分析苏宁API接口,用Python脚本实现
深度分析苏宁API接口,用Python脚本实现
|
3月前
|
前端开发 Shell API
深度分析58同城API接口,用Python脚本实现
58同城为国内知名分类信息平台,涵盖房产、招聘、二手车等多领域。本文基于网页抓包与解析,分享其非官方接口的Python实现方案,分析核心接口特性与反爬应对策略,适用于数据学习与信息聚合。注意:非官方接口存在风险,使用需遵守平台规则。

推荐镜像

更多