python自动化脚本:让工作自动化起来

Python是一种流行的编程语言,以其简洁和易读性而闻名。它提供了大量的库和模块,使其成为自动化各种任务的绝佳选择。

我们将探讨9个Python脚本及其代码,可以帮助您自动化各种任务并提高工作效率。无论您是开发人员、数据分析师还是只是想简化工作流程的人,这些脚本都能满足您的需求。

以下是9个最佳Python脚本,这些脚本可以帮助您自动化各种工作任务,提高工作效率:

1. 自动化文件管理

1.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))

1.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)

1.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))

2. 网页抓取与数据处理

2.1 网页数据抓取

  • 功能:从网站上抓取数据,如新闻标题、产品信息或价格等。

  • 示例代码

    python 复制代码
    import requests
    from bs4 import BeautifulSoup
    
    def scrape_data(url):
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
        # 提取网站中相关数据的代码

2.2 批量下载图片

  • 功能:从网站批量下载图片,保存到指定目录。

  • 示例代码

    python 复制代码
    import requests
    
    def download_images(url_list, save_directory):
        for url in url_list:
            image_response = requests.get(url)
            if image_response.status_code == 200:
                filename = url.split('/')[-1]
                with open(os.path.join(save_directory, filename), "wb") as f:
                    f.write(image_response.content)

3. 文本处理

3.1 拼写检查

  • 功能:检查并纠正文本中的拼写错误。

  • 示例代码

    python 复制代码
    from autocorrect import Speller
    
    def SpellChecker(data):
        spell = Speller(lang='en')
        correction = []
        for word in data.split():
            correction.append(spell(word))
        result = ' '.join(correction)
        return result

3.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)

用Python脚本自动化网站上的表单提交

import requests

def submit_form(url, form_data):

response = requests.post(url, data=form_data)

if response.status_code == 200:

在表单提交后处理响应的代码放在这里

这个Python脚本通过发送带有表单数据的POST请求来自动化网站上的表单提交。

您可以通过提供URL和需要提交的必要表单数据来定制脚本。

![](https://i-blog.csdnimg.cn/blog_migrate/6e9eb9bce60df345228665a93df16fcb.png)

三、文本处理和操作

**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

这个 Python 脚本读取一个文本文件并计算其中包含的单词数量。

它可以用于快速分析文本文档的内容,或者跟踪写作项目中的字数统计。

**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)

这个Python脚本在文件中搜索特定文本,并将其替换为所需的文本。

它可以帮助批量替换某些短语或纠正大型文本文件中的错误。

**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

这个Python脚本生成指定长度的随机文本。它可以用于测试和模拟,甚至可以作为创意写作的随机内容来源。

四、自动化电子邮件

**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()

此Python脚本使您能够向一组收件人发送个性化的电子邮件。您可以自定义发件人的电子邮件、密码、主题、正文以及收件人电子邮件列表。

请注意,出于安全原因,在使用Gmail时应使用特定于应用程序的密码。

**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()

这个Python脚本允许您发送带有文件附件的电子邮件。只需提供发件人的电子邮件、密码、收件人的电子邮件、主题、正文以及要附加的文件路径即可。

**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()

此Python脚本根据指定日期发送自动电子邮件提醒。它对于设置重要任务或事件的提醒非常有用,确保您永远不会错过截止日期。

![](https://i-blog.csdnimg.cn/blog_migrate/0ad965d7f413929ffa7e5eb1b96cca68.png)

五、自动化Excel电子表格

**1.读写Excel**
相关推荐
uppp»25 分钟前
深入理解 Java 反射机制:获取类信息与动态操作
java·开发语言
Yan-英杰27 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
预测模型的开发与应用研究4 小时前
数据分析的AI+流程(个人经验)
人工智能·数据挖掘·数据分析
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化