文件操作:
import os
def list_files(directory):
for root, dirs, files in os.walk(directory):
for file in files: print(os.path.join(root, file))
# 示例用法
list_files('/path/to/directory')
定时任务:
import schedule
import time
def job(): print("定时任务执行!")
# 每小时执行一次
schedule.every().hour.do(job)
while True:
schedule.run_pending()
time.sleep(1)
网页爬虫:
import requests
from bs4 import BeautifulSoup
url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取标题
title = soup.title.string print("网页标题:", title)
电子邮箱发送:
import smtplib
from email.mime.text import MIMEText
def send_email():
msg = MIMEText('这是一封测试邮件', 'plain', 'utf-8')
msg['From'] = 'from@example.com'
msg['To'] = 'to@example.com' msg['Subject'] = '测试邮件'
server = smtplib.SMTP('smtp.example.com', 25)
server.login('username', 'password')
server.sendmail('from@example.com', ['to@example.com'], msg.as_string())
server.quit()
# 发送邮件
send_email()
数据清洗和转换:
import pandas as pd
# 创建DataFrame data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 35, 25, 32]}
df = pd.DataFrame(data)
# 显示数据
print(df)
自动化测试:
import unittest
from calculator import Calculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_addition(self):
self.assertEqual(self.calc.add(2, 3), 5)
def test_subtraction(self):
self.assertEqual(self.calc.subtract(5, 3), 2)
def test_multiplication(self):
self.assertEqual(self.calc.multiply(2, 3), 6)
def test_division(self):
self.assertEqual(self.calc.divide(6, 3), 2)
self.assertRaises(ValueError, self.calc.divide, 10, 0)
if __name__ == '__main__':
unittest.main()
#编写calculator.py文件,实现Calculator类:
python
class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y == 0:
raise ValueError('除数不能为零')
return x / y
PDF处理:
import PyPDF2
def count_pages(pdf_path):
with open(pdf_path, 'rb') as f:
reader = PyPDF2.PdfFileReader(f)
return reader.numPages
# 示例用法
pages = count_pages('/path/to/pdf')
print("PDF页面数:", pages)
数据库操作:
(此处示例代码将连接到SQLite数据库并执行查询,但需要事先创建数据库和表。)
import sqlite3
# 连接到 SQLite 数据库(如果不存在则会创建一个)
conn = sqlite3.connect('test.db')
# 创建一个游标对象,用于执行 SQL 语句
cursor = conn.cursor()
# 创建一个名为 users 的表
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)''')
# 提交事务
conn.commit()
# 关闭连接
conn.close()
import sqlite3
# 连接到 SQLite 数据库
conn = sqlite3.connect('test.db')
# 创建一个游标对象,用于执行 SQL 语句
cursor = conn.cursor()
# 插入一条记录
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 30))
# 提交事务
conn.commit()
# 查询记录
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
# 打印查询结果
for row in rows:
print(row)
# 关闭连接
conn.close()
图像处理
from PIL import Image
def rotate_image(image_path, degrees):
with Image.open(image_path) as img:
rotated_img = img.rotate(degrees)
rotated_img.show()
# 示例用法
rotate_image('/path/to/image.jpg', 90)
定时发送消息:
import schedule
import time
# 定义发送消息的函数
def send_message():
print("发送消息:这是定时发送的消息!")
# 定义定时任务
def schedule_message():
# 安排每隔5秒发送一次消息
schedule.every(5).seconds.do(send_message)
# 安排每天的特定时间发送消息(示例为每天10:00)
schedule.every().day.at("10:00").do(send_message)
# 可以添加更多的定时任务
# 主循环,不断检查是否有任务需要执行
while True:
schedule.run_pending()
time.sleep(1)
# 启动定时发送消息的程序
if __name__ == "__main__":
schedule_message()
自动化表单填写:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://example.com')
# 查找表单元素并填写数据
driver.find_element_by_name('username').send_keys('user') driver.find_element_by_name('password').send_keys('pass')
自动化文档生成:
from docx import Document
def create_document():
doc = Document() doc.add_heading('标题', level=1)
doc.add_paragraph('这是一段文本。')
doc.save('document.docx')
# 创建文档
create_document()
使用第三方库进行自动化任务调度和自动化邮件收取
import schedule
import time
from imapclient import IMAPClient
# 函数用于定时任务执行的示例
def job():
print("任务执行中...")
# 定义任务调度,每隔一段时间执行一次任务
schedule.every(5).minutes.do(job) # 每隔5分钟执行一次任务
# 函数用于自动化邮件收取的示例
def fetch_emails():
# 连接到 IMAP 服务器
server = IMAPClient('imap.example.com')
server.login('your_username', 'your_password')
# 选择邮箱文件夹
server.select_folder('INBOX')
# 检索未读邮件
messages = server.search(['UNSEEN'])
# 处理未读邮件
for uid, message_data in server.fetch(messages, 'RFC822').items():
email_message = email.message_from_bytes(message_data[b'RFC822'])
print('邮件主题:', email_message['Subject'])
# 在这里可以添加处理邮件的逻辑
# 标记邮件为已读
server.set_flags(messages, [b'\\Seen'])
# 关闭连接
server.logout()
# 每隔一段时间执行一次邮件收取任务
schedule.every(30).minutes.do(fetch_emails) # 每隔30分钟执行一次邮件收取任务
# 主循环,不断检查是否有任务需要执行
while True:
schedule.run_pending()
time.sleep(1)