快快收藏!10个Python脚本,轻松实现日常任务自动化

发布时间:2024-12-05 17:27

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

在日常工作中,我们是不是经常遇到一些繁琐、没意义的日常重复任务?面对这些,我的第一反应不是直接动手做,而是去探索:有没有自动化脚本帮助我解放双手,提升工作效率!以下就是我日常工作中经常使用的 10 个自动化脚本,汇总分享给大家,希望帮助大家提升工作效率,专注于更重要的任务!

1、文件重命名

有时候你可能需要批量修改一些文件的名称,比如给文件名添加前缀、后缀,或者按一定规则重新编号。Python 的 os 库可以帮你轻松搞定,如下所示

import os

def batch_rename(directory, prefix):

"""

批量重命名指定目录中的文件,添加指定前缀和编号。

:param directory: 要重命名文件的目录路径

:param prefix: 重命名文件的前缀

"""

for count, filename in enumerate(os.listdir(directory)):

dst = f"{prefix}_{str(count)}.txt"

src = os.path.join(directory, filename)

dst = os.path.join(directory, dst)

os.rename(src, dst)

batch_rename('/path/to/directory', 'file')

2、文件备份

在日常工作中,如果我们需要实现文件的备份功能。Python 的 shutil  可以帮你轻松搞定,如下所示

import shutil

import os

def backup_file(source, destination):

"""

备份文件的函数。

参数:

source (str): 源文件的路径。

destination (str): 目标文件夹的路径。

此函数将源文件复制到目标文件夹。

"""

shutil.copy(source, destination)

backup_file('/path/to/source/file.txt', '/path/to/destination/')

3、自动化Excel数据处理

如果你日常工作经常与 Excel 文件打交道,我们可以使用 Python 处理 Excel 数据非常方便,再也不用手动修改、筛选、汇总了。Python 的 openpyxl 可以帮你轻松搞定,如下所示

from openpyxl import load_workbook

wb = load_workbook('data.xlsx')

sheet = wb.active

for row in sheet.rows:

for cell in row:

print(cell.value)

sheet.cell(row=1, column=1, value='Hello')

wb.save('output.xlsx')

4、 自动化图片处理

利用 Python 强大的图像处理库 Pillow,可以轻松实现图片的缩放、裁剪、旋转、添加水印等操作,如下所示

from PIL import Image

img = Image.open('input.jpg')

img.thumbnail((128, 128))

cropped = img.crop((0, 0, 100, 100))

rotated = img.rotate(45)

watermark = Image.open('mark.png')

img.paste(watermark, (50, 50), mask=watermark)

5、自动化PDF处理

PDF是最常见的电子文档格式之一。利用 PyPDF2 库,你可以自动提取PDF中的文本、合并多个PDF、旋转、加密等,如下所示

from PyPDF2 import PdfFileReader, PdfFileWriter

with open('input.pdf', 'rb') as f:

reader = PdfFileReader(f)

page = reader.getPage(0)

print(page.extractText())

pdf1 = PdfFileReader(open('file1.pdf', 'rb'))

pdf2 = PdfFileReader(open('file2.pdf', 'rb'))

writer = PdfFileWriter()

writer.addPage(pdf1.getPage(0))

writer.addPage(pdf2.getPage(0))

with open('output.pdf', 'wb') as f:

writer.write(f)

6、定时任务

在日常工作中,有时候我们需要定时执行某些后台任务,例如每 3 秒记录一次系统状态或数据更新等。Python 的 schedule 可以帮你轻松搞定,如下所示

import schedule

import time

def job():

"""

定义要执行的任务。

在这个示例中,任务是打印一条消息。

"""

print("Task is running...")

schedule.every(3).seconds.do(job)

while True:

schedule.run_pending()

time.sleep(1)

7、发送电子邮件

有时候你在项目中或者日常工作中,希望有 Python 脚本进行邮件发送。Python 的 smtplib 库可以帮你轻松搞定,如下所示

import smtplib

from email.mime.text import MIMEText

def send_email(subject, body, to_email):

"""

发送电子邮件的函数。

:param subject: 邮件主题

:param body: 邮件正文

:param to_email: 收件人邮箱地址

"""

from_email = "your_email@example.com"

password = "your_password"

msg = MIMEText(body)

msg['Subject'] = subject

msg['From'] = from_email

msg['To'] = to_email

with smtplib.SMTP('smtp.example.com', 587) as server:

server.starttls()

server.login(from_email, password)

server.sendmail(from_email, to_email, msg.as_string())

send_email('Test Subject', 'This is a test email', 'to_email@example.com')

8、 自动化日志分析

服务器日志蕴含了重要的系统运行信息,需要经常查看和分析。你可以用 Python 的 re 模块,可以扫描日志并提取关键数据

import re

pattern = r'ERROR:.*'

with open('app.log', 'r') as f:

for line in f:

match = re.search(pattern, line)

if match:

print(match.group())

9、网页数据抓取

如果我们平时想抓取某个网站的内容或者数据,进行数据分析或者竞对分析,那么 Python 可是网络爬虫的利器。Python 的 requests 和 BeautifulSoup 库可以帮你轻松搞定,如下所示

import requests

from bs4 import BeautifulSoup

def scrape_website(url):

"""

抓取指定 URL 的网页标题。

参数:

url (str): 要抓取的网页地址

返回:

str: 网页标题或错误信息

"""

try:

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'

}

response = requests.get(url, headers=headers)

response.raise_for_status()

soup = BeautifulSoup(response.text, 'html.parser')

return soup.title.text if soup.title else 'No title found'

except requests.exceptions.RequestException as e:

return f"Error fetching the URL: {e}"

if __name__ == "__main__":

print(scrape_website('https://www.baidu.com'))

' 10、监控网站可用性

网站宕机会带来严重的后果和损失,如果能第一时间收到宕机通知,将会极大减少损失。而写个 Python 脚本监控网站可用性很简单

import requests

import smtplib

def notify_user(msg):

server = smtplib.SMTP('smtp.gmail.com', 587)

server.starttls()

server.login('your_email@gmail.com', 'your_password')

server.sendmail('your_email@gmail.com', 'to_email@gmail.com', msg)

server.quit()

try:

response = requests.get('https://www.yourwebsite.com')

if response.status_code != 200:

notify_user('Website is down!')

except:

notify_user('Website is down!')

以上就是 10 个实用的 Python 自动化脚本,是不是对你大有帮助?赶快动手试试,让枯燥的重复工作自动化,让生活更美好!

希望这篇文章能为你提供一些灵感,让你在工作中更游刃有余,告别无聊的重复劳动!如果你还有其他日常任务想要自动化,不妨尝试用Python来实现,让 Python 成为你的 生产力武器!

如果你喜欢本文,欢迎点赞,并且关注我们的微信公众号:Python技术极客,我们会持续更新分享 Python 开发编程、数据分析、数据挖掘、AI 人工智能、网络爬虫等技术文章!让大家在Python 技术领域持续精进提升,成为更好的自己!

添加作者微信(coder_0101),拉你进入行业技术交流群,进行技术交流~

网址:快快收藏!10个Python脚本,轻松实现日常任务自动化 https://www.yuejiaxmz.com/news/view/386313

相关内容

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

随便看看