python10个常用的自动化脚本

2372 篇文章 2 订阅
2238 篇文章 14 订阅

软件测试面试刷题,这个小程序(永久刷题),靠它可以快速找到工作!https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502icon-default.png?t=N7T8https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502

在快节奏的数字化时代,自动化已经成为提升效率的关键词。Python,以其简洁的语法和丰富的库支持,成为编写自动化脚本的首选语言。今天,我们将探索10个实用的Python自动化脚本,它们能够简化日常工作、提升生活品质,让你在日常任务中更加游刃有余。

1. 文件批量重命名

面对一堆杂乱无章的文件名,手动更改费时费力。以下脚本可以批量将文件名中的特定字符替换或增加前缀后缀。

import os
def batch_rename(directory, find_str, replace_str, prefix=''):
    for filename in os.listdir(directory):
        if find_str in filename:
            new_filename = filename.replace(find_str, replace_str)
            new_filename = prefix + new_filename if prefix else new_filename
            os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))
# 示例用法
batch_rename('/path/to/your/directory', 'old_', 'new_', 'updated_')

2. 网页内容抓取

自动抓取网页信息,如新闻标题、天气预报等,是信息收集的有力工具。

import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/news'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for title in soup.find_all('h2', class_='news-title'):
    print(title.text.strip())

3. 定时发送邮件提醒

安排会议、生日祝福或日常提醒,通过邮件自动发送。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import schedule
import time
def send_email():
    sender_email = "your_email@example.com"
    receiver_email = "receiver@example.com"
    password = input("Type your password and press enter: ")
    message = MIMEMultipart("alternative")
    message["Subject"] = "Daily Reminder"
    message["From"] = sender_email
    message["To"] = receiver_email
    text = """\
    Hi,
    This is your daily reminder!
    """
    part = MIMEText(text, "plain")
    message.attach(part)
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())
    server.quit()
schedule.every().day.at("10:30").do(send_email)
while True:
    schedule.run_pending()
    time.sleep(1)

4. 数据备份脚本

定期备份重要文件,保护数据安全。

import shutil
import datetime
source_folder = '/path/to/source'
backup_folder = f'/path/to/backup/{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}'
shutil.copytree(source_folder, backup_folder)
print(f"Backup completed at {backup_folder}")

5. 社交媒体监控

监控社交媒体上的关键词提及,例如微博、Twitter等。

import tweepy
# 需要先在Twitter开发者账户获取API密钥
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
search_query = '#Python'
tweets = api.search(q=search_query,, count=10)
for tweet in tweets:
    print(tweet.user.name, tweet.text)

6. PDF文件合并

将多个PDF文件合并成一个文档。

from PyPDF2 import PdfMerger
pdf_files = ['/path/to/file1.pdf', '/path/to/file2.pdf']
merger = PdfMerger()
for pdf_file in pdf_files:
    merger.append(pdf_file)
merger.write('/path/to/output.pdf')
merger.close()
print("PDFs merged successfully.")

7. 自动化表格处理

使用pandas处理CSV或Excel文件,自动化数据清洗和分析。

import pandas as pd
df = pd.read_csv('data.csv')
# 数据清洗示例:去除空值
df.dropna(inplace=True)
# 数据分析示例:计算平均值
average_score = df['Score'].mean()
print(f"Average Score: {average_score}")

8. 图片批量压缩

自动调整图片大小,节省存储空间。

from PIL import Image
def compress_image(image_path, output_path, quality=90):
    img = Image.open(image_path)
    img.save(output_path, optimize=True, quality=quality)
images_folder = '/path/to/images'
for filename in os.listdir(images_folder):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        img_path = os.path.join(images_folder, filename)
        output_path = os.path.join(images_folder, f"compressed_{filename}")
        compress_image(img_path, output_path)
print("Images compressed.")

9. 网络状态监测

定期检查网络连接状况,确保在线服务稳定。

import urllib.request
import time
def check_internet():
    try:
        urllib.request.urlopen("http://www.google.com", timeout=5)
        print("Internet is connected.")
    except urllib.error.URLError:
        print("No internet connection.")
while True:
    check_internet()
    time.sleep(60)  # 每分钟检查一次

10. 系统资源监控

监控CPU和内存使用情况,预防系统过载。

import psutil
def monitor_resources():
    cpu_percent = psutil.cpu_percent(interval=1)
    memory_info = psutil.virtual_memory()
    print(f"CPU Usage: {cpu_percent}%")
    print(f"Memory Usage: {memory_info.percent}%")
while True:
    monitor_resources()
    time.sleep(5)  # 每5秒检查一次

总结

以上脚本涵盖了日常办公、数据分析、系统维护等多个领域的自动化需求,展现了Python在提升工作效率和生活质量方面的巨大潜力。希望这些建议能够激发你的灵感,让你的日常生活更加智能化和高效。实践是检验真理的唯一标准,不妨从现在开始,根据自己的需求定制专属的自动化解决方案吧!

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

​​​软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

在这里插入图片描述

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值