Python 以其简单易学的语法和强大的库支持,使得它成为实现自动化任务的理想语言.无论是个人日常工作,还是企业的流程优化,Python 都可以通过自动化脚本帮助节省时间、提升效率.以下是10个令人不可思议的 Python 自动化脚本,涵盖了从文件管理、网络爬虫到数据处理的各个领域.
这里插播一条粉丝福利,如果你正在学习Python或者有计划学习Python,想要突破自我,对未来十分迷茫的,可以点击这里获取最新的Python学习资料和学习路线规划(免费分享,记得关注)
1. 文件自动整理脚本
日常工作中,我们经常会面对文件混乱的问题.此脚本可以自动根据文件类型将文件归类到对应的文件夹中.
import os
import shutil
def organize_files(directory):
# 获取目录中的所有文件
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# 跳过目录
if os.path.isdir(file_path):
continue
# 按文件扩展名分类
file_ext = filename.split('.')[-1]
ext_dir = os.path.join(directory, file_ext.upper())
# 如果分类目录不存在,则创建
if not os.path.exists(ext_dir):
os.makedirs(ext_dir)
# 移动文件到分类目录中
shutil.move(file_path, ext_dir)
# 调用函数,将指定目录进行整理
organize_files('/path/to/your/directory')
这个脚本将按文件类型(扩展名)自动整理目录中的文件.
2. 自动发送邮件脚本
此脚本可以通过 SMTP 自动发送邮件,适合用于批量通知、营销邮件等场景.
import smtplib
from email.mime.text import MIMEText
def send_email(sender, password, recipient, subject, message):
# 设置邮件内容
msg = MIMEText(message, 'plain', 'utf-8')
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
# 连接 SMTP 服务器并发送邮件
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(sender, password)
server.sendmail(sender, recipient, msg.as_string())
# 使用脚本发送邮件
send_email("your_email@gmail.com", "your_password", "recipient@example.com", "自动化邮件", "这是通过Python发送的自动化邮件.")
通过这个脚本,可以自动化发送带有自定义内容的邮件.
3. 自动备份文件脚本
将重要的文件自动压缩备份到指定目录,防止文件丢失.
import os
import zipfile
import datetime
def backup_files(source_dir, backup_dir):
# 获取当前日期作为备份文件名的一部分
current_date = datetime.datetime.now().strftime("%Y%m%d")
zip_filename = os.path.join(backup_dir, f"backup_{current_date}.zip")
# 创建压缩文件
with zipfile.ZipFile(zip_filename, 'w') as backup_zip:
for foldername, subfolders, filenames in os.walk(source_dir):
for filename in filenames:
file_path = os.path.join(foldername, filename)
backup_zip.write(file_path, os.path.relpath(file_path, source_dir))
print(f"备份完成:{zip_filename}")
# 调用函数,备份指定目录
backup_files('/path/to/source', '/path/to/backup')
此脚本会将指定目录的所有文件压缩成一个备份文件.
4. 自动登录并填写表单的脚本
结合 Selenium
库,可以自动登录网站并填写表单,例如自动签到、自动报名等.
from selenium import webdriver
from selenium.webdriver.common.by import By
def auto_login_and_fill_form(url, username, password):
# 设置Chrome驱动路径
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
driver.get(url)
# 自动登录
driver.find_element(By.NAME, 'username').send_keys(username)
driver.find_element(By.NAME, 'password').send_keys(password)
driver.find_element(By.ID, 'login_button').click()
# 填写表单(假设有表单)
driver.find_element(By.NAME, 'form_field').send_keys("自动填写内容")
driver.find_element(By.ID, 'submit_button').click()
driver.quit()
# 使用脚本自动登录并填写表单
auto_login_and_fill_form('https://example.com/login', 'your_username', 'your_password')
此脚本自动化登录网站并填写表单,适合用于重复性操作.
5. 自动天气预报通知脚本
通过API获取天气预报,并自动发送通知到手机或邮箱.
import requests
def get_weather(api_key, city):
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric'
response = requests.get(url)
weather_data = response.json()
return weather_data['main']['temp'], weather_data['weather'][0]['description']
# 使用脚本获取并打印天气信息
temp, description = get_weather('your_api_key', 'Beijing')
print(f"北京当前温度: {temp}°C, 天气状况: {description}")
该脚本通过调用开放的天气API获取实时天气信息,并可以拓展为自动发送天气预报通知.
6. 自动化Excel数据处理脚本
使用 pandas
库快速处理Excel数据,例如生成报表或数据分析.
import pandas as pd
def process_excel(file_path):
# 读取Excel文件
df = pd.read_excel(file_path)
# 数据处理,例如计算列总和
df['Total'] = df.sum(axis=1)
# 保存处理后的数据
df.to_excel('processed_data.xlsx', index=False)
# 调用函数处理Excel文件
process_excel('/path/to/excel/file.xlsx')
此脚本自动读取Excel文件,处理数据后生成新的Excel文件.
7. 定时自动化任务脚本
此脚本使用 schedule
库,在指定时间自动执行任务.
import schedule
import time
def job():
print("执行定时任务...")
# 每天上午10点执行任务
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
该脚本可以自动在指定时间执行任务,例如每天定时运行一次备份或发送报告.
8. 自动生成PDF报告的脚本
使用 Fpdf
库生成包含文本和图像的PDF报告.
from fpdf import FPDF
def create_pdf_report(filename, title, content):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", 'B', 16)
pdf.cell(200, 10, title, ln=True, align='C')
pdf.set_font("Arial", '', 12)
pdf.multi_cell(0, 10, content)
pdf.output(filename)
# 使用脚本生成PDF报告
create_pdf_report('report.pdf', '自动化PDF报告', '这是一个自动生成的PDF报告内容.')
此脚本可以自动生成PDF报告,适合用于生成报表、文档等.
9. 网络爬虫自动抓取信息脚本
通过 BeautifulSoup
库自动抓取网页中的信息,如新闻、商品信息等.
import requests
from bs4 import BeautifulSoup
def scrape_news(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 抓取所有新闻标题
for title in soup.find_all('h2'):
print(title.get_text())
# 使用脚本抓取新闻标题
scrape_news('https://example.com/news')
此脚本自动从网页中提取指定内容,适合用于定期抓取最新信息.
10. 自动化社交媒体发布脚本
通过API自动发布消息到社交媒体平台,例如Twitter或微信.
import tweepy
def tweet(message, api_key, api_secret_key, access_token, access_token_secret):
# 使用tweepy进行认证
auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# 发布推文
api.update_status(message)
# 使用脚本发布推文
tweet("这是一个自动发布的推文!", "your_api_key", "your_api_secret", "your_access_token", "your_access_token_secret")
此脚本可以自动化发布社交媒体内容,节省了手动登录发布的时间.
最后,我精心筹备了一份全面的Python学习大礼包,完全免费分享给每一位渴望成长、希望突破自我现状却略感迷茫的朋友。无论您是编程新手还是希望深化技能的开发者,都欢迎加入我们的学习之旅,共同交流进步!
🌟 学习大礼包包含内容:
Python全领域学习路线图:一目了然,指引您从基础到进阶,再到专业领域的每一步学习路径,明确各方向的核心知识点。
超百节Python精品视频课程:涵盖Python编程的必备基础知识、高效爬虫技术、以及深入的数据分析技能,让您技能全面升级。
实战案例集锦:精选超过100个实战项目案例,从理论到实践,让您在解决实际问题的过程中,深化理解,提升编程能力。
华为独家Python漫画教程:创新学习方式,以轻松幽默的漫画形式,让您随时随地,利用碎片时间也能高效学习Python。
互联网企业Python面试真题集:精选历年知名互联网企业面试真题,助您提前备战,面试准备更充分,职场晋升更顺利。
👉 立即领取方式:只需【点击这里】,即刻解锁您的Python学习新篇章!让我们携手并进,在编程的海洋里探索无限可能