您当前的位置: 首页 >> 热门资讯

100个必会的python脚本_《9个顶级Python脚本:实现工作自动化》,一篇读懂

作者:admin 日期:2025-01-03 点击数:0

Python作为一种广泛使用的编程语言,以简洁和易读性而闻名它拥有丰富的库和模块,使其成为自动化任务的理想选择我们将介绍9个Python脚本及其代码,帮助您简化日常任务并提高工作效率无论您是开发人员、数据分析师还是希望简化工作流程的用户,这些脚本都能满足您的需求。

接下来,我们将探讨如何使用Python实现不同领域的自动化任务一、文件管理自动化1. 按扩展名分类文件 # Python脚本用于按文件扩展名对目录中的文件进行分类 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)) 。

此脚本根据文件扩展名将文件移动到相应的子目录中,有助于整理文件夹内容2. 删除空文件夹 # 用Python脚本删除目录中的空文件夹 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) 。

该脚本用于搜索并删除指定目录中的空文件夹,保持文件夹结构整洁3. 批量重命名文件 # 用Python脚本批量重命名文件 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)) 。

此脚本允许用户同时重命名多个文件,方便快捷地修改文件名二、网络爬虫应用1. 网页抓取数据 # 从网站提取数据的Python脚本 import requests from bs4 import BeautifulSoup def scrape_data(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 在此处添加提取具体数据的代码 。

此脚本利用requests和BeautifulSoup库从网页中抓取所需信息2. 批量下载图片 # 批量下载图片的Python脚本 import requests def download_images(url, save_directory): response = requests.get(url) if response.status_code == 200: images = response.json() # 假设API返回一个包含图片URL的JSON数组 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) 。

该脚本可以批量下载网站上的图片,并将其保存到指定目录3. 自动化表单提交 # 自动化网站表单提交的Python脚本 import requests def submit_form(url, form_data): response = requests.post(url, data=form_data) if response.status_code == 200: # 在表单提交后处理响应的代码放在此处 。

此脚本通过发送POST请求来自动化提交表单,适用于需要频繁提交表单的场景三、文本处理与操作1. 统计文本文件中的单词数量 # 计算文本文件中单词数量的Python脚本 def count_words(file_path): with open(file_path, 'r') as f: text = f.read() word_count = len(text.split()) return word_count 。

此脚本读取文本文件并统计其中的单词数量,可用于分析文本文档或跟踪写作进度2. 查找和替换文本 # 查找并替换文件中特定文本的Python脚本 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. 生成随机文本 # 生成随机文本的Python脚本 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 。

此脚本生成指定长度的随机文本,可用于测试或模拟数据四、电子邮件自动化1. 发送个性化邮件 # 向收件人列表发送个性化邮件的Python脚本 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() 。

此脚本可以帮助您向多个收件人发送个性化的电子邮件2. 发送带附件的邮件 # 发送带附件的电子邮件的Python脚本 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() 。

该脚本允许您发送带有附件的电子邮件,方便分享文件3. 自动发送提醒邮件 # 发送自动提醒邮件的Python脚本 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() 。

游戏爱好者的福音!【星界云手机】,云端托管手游,帮你实现24小时不间断游戏。挂机脚本助你完成日常任务,让你的游戏之旅更加轻松,让你成为游戏世界的领军者!

此脚本可以根据设定日期发送提醒邮件,确保重要事项不会被遗忘五、Excel电子表格自动化1. 读写Excel文件 # 读取和写入Excel文件的Python脚本 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) 。

此脚本使用pandas库读取和写入Excel文件,便于处理和分析数据2. 数据分析与可视化 # 使用pandas和matplotlib进行数据分析和可视化的Python脚本 import pandas as pd import matplotlib.pyplot as plt def analyze_and_visualize_data(data): # 在此处添加数据分析和可视化的代码 pass 。

此脚本结合pandas和matplotlib库进行数据分析和可视化,帮助用户探索数据集并生成图表3. 合并多个工作表 # 将多个工作表合并为一个的Python脚本 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) 。

该脚本将多个工作表的数据合并到一个工作表中,方便进一步分析六、数据库交互1. 连接数据库并执行查询 # 连接到数据库并执行查询的Python脚本 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 。

此脚本允许用户连接到SQLite数据库并执行SQL查询2. 数据备份与恢复 # 备份和恢复数据库的Python脚本 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) 。

该脚本提供创建和恢复数据库备份的功能,保护数据安全七、图像编辑自动化1. 调整图像大小和裁剪 # 调整图像大小和裁剪的Python脚本 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) 。

此脚本使用PIL库调整图像大小和裁剪图像,适用于准备不同分辨率的图片2. 添加水印 # 给图像添加水印的Python脚本 from PIL import Image, ImageDraw, 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) 。

该脚本可以给图像添加自定义水印,保护版权3. 创建缩略图 # 创建图像缩略图的Python脚本 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) 。

此脚本用于创建图像的缩略图,适用于生成预览图片八、数据清洗与转换1. 删除重复项 # 从数据集中删除重复项的Python脚本 import pandas as pd def remove_duplicates(data_frame): cleaned_data = data_frame.drop_duplicates() return cleaned_data 。

此脚本用于清理数据集中的重复行,确保数据完整性和准确性2. 数据规范化 # 数据归一化的Python脚本 import pandas as pd def normalize_data(data_frame): normalized_data = (data_frame - data_frame.min()) / (data_frame.max() - data_frame.min()) return normalized_data 。

该脚本使用最小-最大归一化技术对数据进行规范化,使不同特征之间的比较更加直观3. 处理缺失值 # 处理数据集中缺失值的Python脚本 import pandas as pd def handle_missing_values(data_frame): filled_data = data_frame.fillna(method='ffill') return filled_data 。

此脚本使用前向填充方法处理数据集中的缺失值,确保数据完整性九、PDF文件操作1. 提取PDF中的文本 # 从PDF中提取文本的Python脚本 import PyPDF2 def extract_text_from_pdf(file_path): with open(file_path, 'rb') as f: pdf_reader = PyPDF2.PdfReader(f) text = '' for page_num in range(len(pdf_reader.pages)): page = pdf_reader.pages[page_num] text += page.extract_text() return text 。

此脚本使用PyPDF2库从PDF文件中提取文本内容2. 合并多个PDF文件 # 合并多个PDF文件的Python脚本 import PyPDF2 def merge_pdfs(input_paths, output_path): pdf_merger = PyPDF2.PdfMerger() for path in input_paths: with open(path, 'rb') as f: pdf_merger.append(f) with open(output_path, 'wb') as f: pdf_merger.write(f) 。

该脚本将多个PDF文件合并成一个,方便管理和分发3. 添加密码保护 # 为PDF添加密码保护的Python脚本 import PyPDF2 def add_password_protection(input_path, output_path, password): with open(input_path, 'rb') as f: pdf_reader = PyPDF2.PdfReader(f) pdf_writer = PyPDF2.PdfWriter() for page_num in range(len(pdf_reader.pages)): page = pdf_reader.pages[page_num] pdf_writer.add_page(page) pdf_writer.encrypt(password) with open(output_path, 'wb') as output_file: pdf_writer.write(output_file) 。

此脚本为PDF文件添加密码保护,确保文件的安全性当前Python仍然是大趋势和热门话题,相信对于很多初学者来说,好的资料必不可少你是否想探索Python的奥秘?你是否困惑于难以系统性学习Python?你是否在学习过程中遇到问题却无人可请教?……如果你有以上问题,那就快来免费参与Python快速入门课!限时0元学习课程。

ENDPython学习交流群欢迎大家加入我们的Python学习交流群除了有Python学习、技能提升、工作各个环节的指导交流外,群内会定期分享行业资讯、实用工具资料包、书籍推荐、大咖分享会等信息,Python干货信息不断发送!。

感受游戏的极致乐趣,尽在【星界云手机】!云端托管手游,挂机脚本助你完成繁杂任务,让你的游戏之旅更加顺畅、畅快。释放你的双手,成为游戏世界的主宰!

本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:631580315@qq.com

标签: