1. 自动化文件管理
1.1 批量重命名文件
假设你有一批文件,文件名需要按一定规则批量修改,可以使用 os 和 re 库来实现。
import os import re # 设置目录路径 directory = 'c:/path/to/your/files' # 获取文件列表 files = os.listdir(directory) # 批量重命名文件 for filename in files: new_name = re.sub(r'old_pattern', 'new_pattern', filename) # 替换文件名中的内容 os.rename(os.path.join(directory, filename), os.path.join(directory, new_name)) print("文件重命名完成!")
1.2 自动分类文件
根据文件扩展名自动将文件分类到不同的文件夹中。
import os import shutil # 设置目录路径 directory = 'c:/path/to/your/files' # 获取文件列表 files = os.listdir(directory) # 定义文件分类规则 file_types = { 'images': ['.jpg', '.jpeg', '.png', '.gif'], 'documents': ['.pdf', '.txt', '.docx'], 'audio': ['.mp3', '.wav'] } # 创建文件夹(如果不存在) for folder in file_types: if not os.path.exists(os.path.join(directory, folder)): os.makedirs(os.path.join(directory, folder)) # 移动文件 for filename in files: file_path = os.path.join(directory, filename) if os.path.isfile(file_path): moved = false for folder, extensions in file_types.items(): if any(filename.endswith(ext) for ext in extensions): shutil.move(file_path, os.path.join(directory, folder, filename)) moved = true break if not moved: print(f"文件 {filename} 没有分类!") print("文件分类完成!")
2. 自动化定时任务
2.1 使用 schedule 库定时执行任务
schedule 是一个 python 库,专门用于调度定时任务。你可以使用它来设置定时执行的任务。
import schedule import time # 定义要执行的任务 def job(): print("任务开始执行!") # 每隔 10 秒执行一次任务 schedule.every(10).seconds.do(job) # 持续运行任务 while true: schedule.run_pending() time.sleep(1)
2.2 使用 apscheduler 执行复杂定时任务
apscheduler 是一个功能更强大的调度任务库,支持多种调度方式。
from apscheduler.schedulers.blocking import blockingscheduler import datetime # 定义要执行的任务 def print_time(): print(f"当前时间:{datetime.datetime.now()}") # 创建调度器 scheduler = blockingscheduler() # 添加任务,定时每分钟执行 scheduler.add_job(print_time, 'interval', minutes=1) # 启动调度器 scheduler.start()
3. 自动化发送邮件
使用 smtplib 库,可以自动化发送邮件,比如定时向客户或团队成员发送报告。
import smtplib from email.mime.text import mimetext from email.mime.multipart import mimemultipart def send_email(subject, body, to_email): from_email = "your_email@gmail.com" password = "your_password" # 设置邮件内容 msg = mimemultipart() msg['from'] = from_email msg['to'] = to_email msg['subject'] = subject msg.attach(mimetext(body, 'plain')) # 发送邮件 try: server = smtplib.smtp('smtp.gmail.com', 587) server.starttls() server.login(from_email, password) text = msg.as_string() server.sendmail(from_email, to_email, text) server.quit() print("邮件发送成功!") except exception as e: print(f"邮件发送失败:{e}") # 调用函数发送邮件 send_email("自动化报告", "这是自动化发送的邮件内容", "recipient_email@example.com")
4. 自动化网络爬虫
使用 requests 和 beautifulsoup 库,可以自动化爬取网页内容,并将其存储到文件中。
import requests from bs4 import beautifulsoup # 定义爬取目标网址 url = "https://example.com" # 发送 http 请求获取网页内容 response = requests.get(url) # 解析网页内容 soup = beautifulsoup(response.text, 'html.parser') # 获取页面标题 title = soup.title.string # 打印标题 print(f"网页标题: {title}")
5. 自动化数据处理
5.1 使用 pandas 库处理数据
如果你经常需要处理 csv 文件或 excel 文件,可以使用 pandas 库来实现数据的读取、处理和导出。
import pandas as pd # 读取 csv 文件 df = pd.read_csv('data.csv') # 进行数据处理(例如:筛选大于 100 的值) df_filtered = df[df['column_name'] > 100] # 保存处理后的数据到新的 csv 文件 df_filtered.to_csv('filtered_data.csv', index=false) print("数据处理完成!")
5.2 定时备份数据库
可以通过 python 脚本定时备份数据库,减少人工干预。
import mysql.connector import datetime import os def backup_database(): # 数据库连接配置 db = mysql.connector.connect( host="localhost", user="your_user", password="your_password", database="your_database" ) # 创建备份文件名 backup_filename = f"backup_{datetime.datetime.now().strftime('%y%m%d_%h%m%s')}.sql" # 使用 mysqldump 进行备份 os.system(f"mysqldump -u your_user -p'your_password' your_database > {backup_filename}") print(f"数据库备份完成!备份文件: {backup_filename}") # 定时备份 backup_database()
6. 自动化图像处理
如果你需要自动处理图像文件(例如,批量调整大小、转换格式等),可以使用 pillow 库。
from pil import image import os # 设置图像目录 image_directory = 'c:/path/to/your/images' # 获取所有图像文件 files = os.listdir(image_directory) # 批量调整图像大小 for filename in files: if filename.endswith('.jpg'): image_path = os.path.join(image_directory, filename) with image.open(image_path) as img: img = img.resize((800, 600)) # 调整大小为 800x600 img.save(os.path.join(image_directory, f"resized_{filename}")) print("图像处理完成!")
7. 自动化 web 操作
如果你需要自动化与网页的交互,可以使用 selenium 来模拟浏览器操作。
from selenium import webdriver # 设置 webdriver driver = webdriver.chrome(executable_path="path/to/chromedriver") # 打开网页 driver.get("https://example.com") # 查找并点击一个按钮 button = driver.find_element_by_xpath("//button[@id='submit']") button.click() # 获取网页内容 page_content = driver.page_source print(page_content) # 关闭浏览器 driver.quit()
总结
使用 python 自动化日常任务可以极大地提高效率并减少重复性工作。通过 python 中的各种库(如 os、shutil、schedule、smtplib、requests、pandas、pillow 等),你可以轻松实现文件管理、定时任务、邮件发送、网页爬取、数据处理等多种自动化任务。
到此这篇关于python自动化处理日常任务的示例代码的文章就介绍到这了,更多相关python自动化处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论