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

发布时间:2024-12-11 18:07

用Python编写简单自动化任务脚本 #生活乐趣# #日常生活趣事# #生活趣味分享# #科技小发明#

引言

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

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

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

11. 文件整理

Python 提供了一种高效的自动化文件整理方法,特别是对于删除或移动旧文件,以维护目录的整洁有序。

下面是一个简单的脚本示例,它利用 os 和 time 模块删除超过一定天数的旧文件。

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 的 datetime 和 asyncio 模块,可以开发出任务追踪或提醒系统。

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

本文由mdnice多平台发布

网址:21个Python脚本自动执行日常任务(2) https://www.yuejiaxmz.com/news/view/445607

相关内容

10个Python脚本自动化日常任务
十个 Python 脚本来自动化你的日常任务
10个 Python 脚本来自动化你的日常任务
10个Python脚本,轻松实现日常任务自动化!
10个Python脚本轻松实现日常任务自动化
10个Python自动化脚本,让日常任务轻松便捷!
【10个Python脚本来自动化你的日常任务】
10个Python脚本来自动化你的日常任务
10 个 Python 脚本来自动化你的日常任务
十个Python脚本,轻松实现日常任务自动化

随便看看