拒绝手动搬砖:9大Python日常自动化实战代码片段
大家好,我是提米哥!作为开发者,你是不是每天都在做很多重复的“搬砖”活儿?自动化就是让软件或机器替你干这些无聊的手工活,把你彻底解放出来。Python因为好学且工具库丰富,绝对是咱们搞自动化的最佳武器。今天提米哥给大家整理了9个非常接地气的真实场景,用最通俗的话讲明白,直接抄代码就能跑!
1. 自动发邮件
再也不用每天定时去邮箱发日报了!用Python的 smtplib 库,你可以让程序自动帮你发邮件。
import smtplib
from email.mime.text import MIMEText
# 定义邮件的各种参数
subject = "Automated Email" # 邮件主题
body = "This is an automated email sent using Python" # 邮件正文内容
to_email = "recipient@example.com" # 收件人邮箱
from_email = "sender@example.com" # 发件人邮箱
password = "your_password" # 发件人邮箱密码或授权码
# 创建一个文本邮件对象
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = from_email
msg["To"] = to_email
# 连接邮箱服务器并发送邮件
server = smtplib.SMTP("smtp.example.com", 587) # 填入你的邮箱SMTP服务器和端口
server.starttls() # 启用安全传输
server.login(from_email, password) # 登录邮箱
server.sendmail(from_email, to_email, msg.as_string()) # 发送邮件
server.quit() # 退出连接
2. 自动整理文件
电脑里下载的文件乱七八糟?用 os 和 shutil 库,你可以一键把某个文件夹里的所有文件移动到另一个指定的地方。
import os
import shutil
# 定义源文件夹(要移动的文件在哪)和目标文件夹(要移到哪去)
src_dir = "/path/to/source/directory"
dst_dir = "/path/to/destination/directory"
# 遍历源文件夹里的所有文件,把它们全都搬到目标文件夹
for filename in os.listdir(src_dir):
shutil.move(os.path.join(src_dir, filename), dst_dir)
3. 自动发社交媒体动态
想定时发推文?用 requests 和 json 库调用推特(Twitter)的API,程序就能替你在社交媒体上发声。
import requests
import json
# 填入你在推特开发者平台申请的API密钥和令牌
api_key = "your_api_key"
api_secret = "your_api_secret"
access_token = "your_access_token"
access_token_secret = "your_access_token_secret"
# 定义你要发的推文内容
tweet_text = "This is an automated tweet sent using Python"
# 使用密钥进行身份验证,然后发送推文请求
auth = requests.auth.HTTPBasicAuth(api_key, api_secret)
response = requests.post("https://api.twitter.com/1.1/statuses/update.json", auth=auth, data={"status": tweet_text})
4. 自动填表格数据
不想手动往Excel或Google表格里一条条敲数据?用 pandas 结合Google Sheets的API,几行代码就能自动把数据填进线上表格。
import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledClientFlow
from google.auth.transport.requests import Request
# 定义Google表格的授权范围和凭证(这里省略了获取creds的具体过程,实际使用需补全)
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
creds = None
# 定义你要操作的表格ID和具体的单元格范围
spreadsheet_id = "your_spreadsheet_id"
range_name = "Sheet1!A1:B2"
# 把数据[[1, 2], [3, 4]]自动写入到指定的表格范围内
service = build("sheets", "v4", credentials=creds)
body = {"values": [[1, 2], [3, 4]]}
result = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=range_name, body=body).execute()
5. 自动监控网站状态
怕自己的网站挂了不知道?用 requests 库写个小脚本,定时去请求你的网站,如果状态码不是200,就说明网站可能宕机了。
import requests
# 定义你要监控的网站网址
url = "https://www.example.com"
# 请求这个网址,检查返回的状态码
response = requests.get(url)
if response.status_code == 200:
print("Website is up") # 状态码200,网站正常运行
else:
print("Website is down") # 状态码异常,网站挂了
6. 自动备份重要文件
重要文件怕丢失?写个定时任务,每天用 shutil 自动把文件复制一份到备份盘里。
import shutil
import os
# 定义你要备份的文件夹和备份存放的文件夹
src_dir = "/path/to/source/directory"
dst_dir = "/path/to/destination/directory"
# 遍历源文件夹,把每个文件都复制到备份文件夹里
for filename in os.listdir(src_dir):
shutil.copy2(os.path.join(src_dir, filename), dst_dir) # copy2会保留文件的原始修改时间等元信息
7. 自动生成销售报表
老板每天要看销售数据?用 pandas 把数据整理好,一键导出成CSV报表文件,直接发给他。
import pandas as pd
# 定义你的销售数据(比如日期和对应的销售额)
sales_data = {"Date": ["2022-01-01", "2022-01-02", "2022-01-03"], "Sales": [100, 200, 300]}
# 把数据转成表格格式,然后保存为名为sales_report.csv的报表文件
df = pd.DataFrame(sales_data)
df.to_csv("sales_report.csv", index=False) # index=False表示不保存行号
8. 自动批量处理图片
网上下载的图片尺寸不一?用 Pillow 库,瞬间把几百张图片统一缩放到你想要的尺寸。
from PIL import Image
# 定义你要处理的图片文件名
image_file = "image.jpg"
# 打开图片,把它缩放为800x600的尺寸,然后另存为新图片
img = Image.open(image_file)
img = img.resize((800, 600)) # 设置你想要的新尺寸
img.save("resized_image.jpg") # 保存处理后的图片
9. 自动剪辑视频片段
想做短视频但不想用复杂的剪辑软件?用 moviepy 库,代码就能帮你自动把长视频裁剪成短片段。
# 导入moviepy的视频编辑模块(注:运行此代码需提前安装moviepy库)
from moviepy.editor import VideoFileClip
# 加载原始视频文件,并裁剪从第10秒到第20秒的片段,最后保存为新视频
# clip = VideoFileClip("long_video.mp4").subclip(10, 20)
# clip.write_videofile("short_clip.mp4")
提米哥总结:这9个场景只是Python自动化的冰山一角。把重复的工作交给代码,你才能腾出精力去做更有价值的事情。赶紧挑一个你最头疼的日常活儿,复制代码跑起来吧!
