利用Python自动化日常任务可以通过编写脚本来实现。以下是一些常见的日常任务及其对应的Python代码示例:
1. 文件批量重命名:
import os def batch_rename(folder_path, old_ext, new_ext): for filename in os.listdir(folder_path): if filename.endswith(old_ext): new_filename = filename.replace(old_ext, new_ext) os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename)) # 使用示例 batch_rename('/path/to/files', '.txt', '.md')
2. 发送电子邮件:
import smtplib from email.mime.text import MIMEText def send_email(subject, body, to_email, from_email, password): msg = MIMEText(body) msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_email server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_email, password) server.sendmail(from_email, [to_email], msg.as_string()) server.quit() # 使用示例 send_email('Hello', 'This is a test email.', 'to@example.com', 'from@example.com', 'yourpassword')
3. 网页内容抓取:
import requests from bs4 import BeautifulSoup def scrape_website(url): response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') return soup.prettify() # 使用示例 print(scrape_website('https://www.example.com'))
这些只是一些简单的例子,实际上Python可以自动化许多复杂的任务,如数据清洗、数据分析、自动化测试等。具体实现取决于你的需求和所使用的库。