1、批量文件重命名神器在工作中,我们常常需要对大量文件进行批量重命名,Python帮你轻松搞定!
import os
def batch_rename(path, prefix='', suffix=''):
for i, filename in enumerate(os.listdir(path)):
new_name = f"{prefix}{i:03d}{suffix}{os.path.splitext(filename)[1]}"
old_file = os.path.join(path, filename)
new_file = os.path.join(path, new_name)
os.rename(old_file, new_file)
# 使用示例:
batch_rename('/path/to/your/directory', 'file_', '.txt')
2、自动发送邮件通知告别手动发送,用Python编写定时发送邮件的自动化脚本。
import smtplib
from email.mime.text import MIMEText
def send_email(to_addr, subject, content):
smtp_server = 'smtp.example.com'
username = '[email protected]'
password = 'your-password'
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = username
msg['To'] = to_addr
server = smtplib.SMTP(smtp_server, 587)
server.starttls()
server.login(username, password)
server.sendmail(username, to_addr, msg.as_string())
server.quit()
# 使用示例:
send_email('[email protected]', '每日报告提醒', '今日报告已生成,请查收。')
3、定时任务自动化执行使用Python调度库,实现定时执行任务的自动化脚本。
import schedule
import time
def job_to_schedule():
print("当前时间:", time.ctime(), "任务正在执行...")
# 定义每天9点执行任务
schedule.every().day.at("09:00").do(job_to_schedule)
while True:
schedule.run_pending()
time.sleep(1)
# 使用示例:
# 运行此脚本后,每天上午9点会自动打印当前时间及提示信息
4、数据库操作自动化简化数据库管理,Python帮你自动化执行CRUD操作。
import sqlite3
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
print(f"成功连接到SQLite数据库:{db_file}")
except Error as e:
print(e)
return conn
def insert_data(conn, table_name, data_dict):
keys = ', '.join(data_dict.keys())
values = ', '.join(f"'{