1. 批量重命名指定目录中的文件
import os
def batch_rename_files(directory, prefix):
i = 1
for filename in os.listdir(directory):
ext = os.path.splitext(filename)[1]
new_name = f"{prefix}_{i}{ext}"
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
i += 1
batch_rename_files('/path/to/directory', 'file')
2. 下载指定网页的内容
import requests
def download_page_content(url, output_file):
response = requests.get(url)
with open(output_file, 'w') as file:
file.write(response.text)
download_page_content('http://example.com', 'page.html')
3. 清理数据文件
import pandas as pd
def clean_data_file(file_path):
df = pd.read_csv(file_path)
df.dropna(inplace=True)
df.to_csv(file_path, index=False)
clean_data_file('data.csv')
4. 定时执行任务
import schedule
import time
def scheduled_task():
print("Task executed")
schedule.every().day.at("1:0").do(scheduled_task)
while True:
schedule.run_pending()
time.sleep(1)
5. 邮件发送
import smtplib
from email.mime.text import MIMEText
def send_email(subject, message, to_email):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = 'you@example.com'
msg['To'] = to_email
s = smtplib.SMTP('localhost')
s.sendmail('you@example.com', [to_email], msg.as_string())
s.quit()
send_email('Your Report', 'Here is your report.Please check it.', 'recipient@example.com')