Python以其简单易读的特性而声名鹊起,是一门备受欢迎的编程语言。其丰富的库和模块使其成为自动化各种任务的理想选择。在下面的集合中,提供了17个多功能的Python脚本,可帮助您简化工作流程,高效节省时间。
1. 自动化文件管理
1.1 对目录中的文件进行排序
import os
from shutil import move
def sort_files(directory_path):
for filename in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, filename)):
file_extension = filename.split('.')[-1]
destination_directory = os.path.join(directory_path, file_extension)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))
1.2 删除空文件夹
import os
def remove_empty_folders(directory_path):
for root, dirs, files in os.walk(directory_path, topdown=False):
for folder in dirs:
folder_path = os.path.join(root, folder)
if not os.listdir(folder_path):
os.rmdir(folder_path)
1.3 重命名多个文件
import os
def rename_files(directory_path, old_name, new_name):
for filename in os.listdir(directory_path):
if old_name in filename:
new_filename = filename.replace(old_name, new_name)
os.rename(os.path.join(directory_path, filename), os.path.join(directory_path, new_filename))
2. 使用Python进行网页抓取
2.1 从网站提取数据
import requests
from bs4 import BeautifulSoup
def scrape_data(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Your code here to extract relevant data from the website
2.2 从网站下载图像
import requests
def download_images(url, save_directory):
response = requests.get(url)
if response.status_code == 200:
images = response.json() # Assuming the API returns a JSON array of image URLs
for index, image_url in enumerate(images):
image_response = requests.get(image_url)
if image_response.status_code == 200:
with open(f"{save_directory}/image_{index}.jpg", "wb") as f:
f.write(image_response.content)
2.3 自动提交表单
import requests
def submit_form(url, form_data):
response = requests.post(url, data=form_data)
if response.status_code == 200:
# Your code here to handle the response after form submission
3. 文本处理和操作
3.1 计算文本文件中的字数
def count_words(file_path):
with open(file_path, 'r') as f:
text = f.read()
word_count = len(text.split())
return word_count
3.2 查找并替换文本文件中的文本
def find_replace(file_path, search_text, replace_text):
with open(file_path, 'r') as f:
text = f.read()
modified_text = text.replace(search_text, replace_text)
with open(file_path, 'w') as f:
f.write(modified_text)
3.3 生成随机文本
import random
import string
def generate_random_text(length):
letters = string.ascii_letters + string.digits + string.punctuation
random_text = ''.join(random.choice(letters) for i in range(length))
return random_text
4. 电子邮件自动化
4.1 发送个性化电子邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_personalized_email(sender_email, sender_password, recipients, subject, body):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
for recipient_email in recipients:
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
4.2 通过电子邮件发送文件附件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment(sender_email, sender_password, recipient_email, subject, body, file_path):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
with open(file_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {file_path}")
message.attach(part)
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
4.3 自动邮件提醒
import smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta
def send_reminder_email(sender_email, sender_password, recipient_email, subject, body, reminder_date):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
now = datetime.now()
reminder_date = datetime.strptime(reminder_date, '%Y-%m-%d')
if now.date() == reminder_date.date():
message = MIMEText(body, 'plain')
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
5. 自动化Excel电子表格
5.1 Excel读&写
import pandas as pd
def read_excel(file_path):
df = pd.read_excel(file_path)
return df
def write_to_excel(data, file_path):
df = pd.DataFrame(data)
df.to_excel(file_path, index=False)
5.2 数据分析和可视化
import pandas as pd
import matplotlib.pyplot as
plt
def analyze_and_visualize_data(data):
# Your code here for data analysis and visualization
pass
5.3 合并多个工作表
import pandas as pd
def merge_sheets(file_path, output_file_path):
xls = pd.ExcelFile(file_path)
df = pd.DataFrame()
for sheet_name in xls.sheet_names:
sheet_df = pd.read_excel(xls, sheet_name)
df = df.append(sheet_df)
df.to_excel(output_file_path, index=False)
6. 与数据库交互
6.1 连接到一个数据库
import sqlite3
def connect_to_database(database_path):
connection = sqlite3.connect(database_path)
return connection
def execute_query(connection, query):
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
return result
6.2 执行SQL查询
import sqlite3
def execute_query(connection, query):
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
return result
6.3 数据备份与恢复
import shutil
def backup_database(database_path, backup_directory):
shutil.copy(database_path, backup_directory)
def restore_database(backup_path, database_directory):
shutil.copy(backup_path, database_directory)
7. 社交媒体自动化
7.1 发布内容到Twitter和Facebook
from twython import Twython
import facebook
def post_to_twitter(api_key, api_secret, access_token, access_token_secret, message):
twitter = Twython(api_key, api_secret, access_token, access_token_secret)
twitter.update_status(status=message)
def post_to_facebook(api_key, api_secret, access_token, message):
graph = facebook.GraphAPI(access_token)
graph.put_object(parent_object='me', connection_name='feed', message=message)
7.2 社交媒体自动共享
import random
def get_random_content():
# Your code here to retrieve random content from a list or database
pass
def post_random_content_to_twitter(api_key, api_secret, access_token, access_token_secret):
content = get_random_content()
post_to_twitter(api_key, api_secret, access_token, access_token_secret, content)
def post_random_content_to_facebook(api_key, api_secret, access_token):
content = get_random_content()
post_to_facebook(api_key, api_secret, access_token, content)
7.3 抓取社交媒体数据
import requests
def scrape_social_media_data(url):
response = requests.get(url)
# Your code here to extract relevant data from the response
8. 自动化系统任务
8.1 管理系统进程
import psutil
def get_running_processes():
return [p.info for p in psutil.process_iter(['pid', 'name', 'username'])]
def kill_process_by_name(process_name):
for p in psutil.process_iter(['pid', 'name', 'username']):
if p.info['name'] == process_name:
p.kill()
8.2 使用Cron安排任务
from crontab import CronTab
def schedule_task(command, schedule):
cron = CronTab(user=True)
job = cron.new(command=command)
job.setall(schedule)
cron.write()
8.3 自动邮件提醒
import psutil
def check_disk_space(minimum_threshold_gb):
disk = psutil.disk_usage('/')
free_space_gb = disk.free / (2**30) # Convert bytes to GB
if free_space_gb < minimum_threshold_gb:
# Your code here to send an alert (email, notification, etc.)
pass
9. 自动化图像编辑
9.1 图像大小调整和裁剪
from PIL import Image
def resize_image(input_path, output_path, width, height):
image = Image.open(input_path)
resized_image = image.resize((width, height), Image.ANTIALIAS)
resized_image.save(output_path)
def crop_image(input_path, output_path, left, top, right, bottom):
image = Image.open(input_path)
cropped_image = image.crop((left, top, right, bottom))
cropped_image.save(output_path)
9.2 为图像添加水印
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def add_watermark(input_path, output_path, watermark_text):
image = Image.open(input_path)
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial.ttf', 36)
draw.text((10, 10), watermark_text, fill=(255, 255, 255, 128), font=font)
image.save(output_path)
9.3 创建图像缩略图
from PIL import Image
def create_thumbnail(input_path, output_path, size=(128, 128)):
image = Image.open(input_path)
image.thumbnail(size)
image.save(output_path)
这套脚本集涵盖了广泛的领域,涉及文件管理、网页抓取、文本处理、电子邮件自动化、Excel电子表格处理、数据库交互、社交媒体自动化、系统任务管理以及图像编辑等多个方面。根据您的具体需求,您可以有选择地应用其中的脚本,以便更全面、高效地简化和优化您的工作流程。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:分享17个Python超级好用提高工作效率的自动化脚本 - Python技术站