实用的 Python 小脚本

devtools/2024/10/23 17:59:01/

一、引言

在日常办公和电脑使用中,我们经常会遇到一些重复性的任务或需要快速获取特定信息的情况。Python 作为一种强大而灵活的编程语言,可以用来编写各种小脚本,以自动化这些任务并提高工作效率。本文将介绍一些 Python 常用的小脚本,包括文件管理、数据处理、电脑信息查询等方面,帮助读者更好地利用 Python 解决实际问题。

二、文件管理脚本

(一)批量重命名文件

在处理大量文件时,手动重命名文件是一项繁琐的任务。使用 Python 可以轻松实现批量重命名文件。以下是一个示例脚本:

import osdef batch_rename(directory, prefix):for count, filename in enumerate(os.listdir(directory)):dst = f"{prefix}{str(count)}.txt"src = os.path.join(directory, filename)dst = os.path.join(directory, dst)os.rename(src, dst)directory = "path/to/your/directory"
prefix = "new_file_"
batch_rename(directory, prefix)

这个脚本遍历指定目录中的所有文件,并以给定的前缀和序号重命名它们。

(二)文件备份

定期备份重要文件是一个好习惯。以下是一个简单的文件备份脚本:

import shutil
import os
import timesource_directory = "path/to/source/directory"
backup_directory = "path/to/backup/directory"def backup_files():timestamp = time.strftime("%Y%m%d%H%M%S")backup_folder = os.path.join(backup_directory, f"backup_{timestamp}")os.makedirs(backup_folder)for filename in os.listdir(source_directory):source_file = os.path.join(source_directory, filename)destination_file = os.path.join(backup_folder, filename)shutil.copy2(source_file, destination_file)backup_files()

这个脚本将指定源目录中的文件备份到另一个目录,并在备份文件夹名称中添加时间戳。

三、数据处理脚本

(一)CSV 文件数据处理

假设你有一个 CSV 文件,需要对其中的数据进行一些处理,比如提取特定列的数据或进行数据清洗。以下是一个示例脚本:

import pandas as pddef process_csv(file_path):df = pd.read_csv(file_path)# 提取特定列的数据column_data = df["column_name"]# 进行数据清洗,例如去除空值cleaned_data = column_data.dropna()return cleaned_datafile_path = "path/to/your/csv/file.csv"
processed_data = process_csv(file_path)
print(processed_data)

这个脚本使用 pandas 库读取 CSV 文件,并进行特定的数据处理操作。

(二)文本文件内容统计

如果你需要统计一个文本文件中的单词数量、行数等信息,可以使用以下脚本:

def count_words_and_lines(file_path):with open(file_path, "r") as file:lines = file.readlines()word_count = 0for line in lines:words = line.split()word_count += len(words)return len(lines), word_countfile_path = "path/to/your/text/file.txt"
line_count, word_count = count_words_and_lines(file_path)
print(f"Lines: {line_count}, Words: {word_count}")

这个脚本打开一个文本文件,统计其中的行数和单词数量。

四、电脑信息查询脚本

(一)获取电脑硬件信息

可以使用 Python 的第三方库来获取电脑的硬件信息,比如 CPU 型号、内存大小等。以下是一个使用 psutil 库的示例:

import psutildef get_computer_info():cpu_info = psutil.cpu_freq()memory_info = psutil.virtual_memory()disk_info = psutil.disk_usage('/')print(f"CPU Frequency: {cpu_info.current} MHz")print(f"Memory Usage: {memory_info.used / (1024 * 1024 * 1024)} GB")print(f"Disk Usage: {disk_info.used / (1024 * 1024 * 1024)} GB")get_computer_info()

这个脚本使用 psutil 库获取电脑的 CPU 频率、内存使用情况和磁盘使用情况。

(二)查询电脑 IP 地址

以下是一个获取电脑 IP 地址的脚本:

import socketdef get_ip_address():hostname = socket.gethostname()ip_address = socket.gethostbyname(hostname)return ip_addressprint(get_ip_address())

这个脚本使用 socket 库获取电脑的 IP 地址。

五、日常办公辅助脚本

(一)自动发送邮件

在一些情况下,你可能需要自动发送邮件通知。以下是一个使用 smtplib 库发送邮件的示例:

import smtplib
from email.mime.text import MIMETextdef send_email(subject, body, to_email):from_email = "your_email@gmail.com"password = "your_password"msg = MIMEText(body)msg['Subject'] = subjectmsg['From'] = from_emailmsg['To'] = to_emailserver = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(from_email, password)server.sendmail(from_email, to_email, msg.as_string())server.quit()subject = "Test Email"
body = "This is a test email sent from Python."
to_email = "recipient_email@gmail.com"
send_email(subject, body, to_email)

这个脚本使用 Gmail 的 SMTP 服务器发送一封邮件,你需要将自己的邮箱地址和密码替换到相应位置。

(二)定时提醒

如果你需要一个定时提醒工具,可以使用以下脚本:

import time
import winsounddef set_reminder(message, delay):time.sleep(delay)print(message)winsound.Beep(1000, 1000)message = "Time for a break!"
delay = 3600  # 设置提醒时间为 1 小时(3600 秒)
set_reminder(message, delay)

这个脚本在指定的延迟时间后打印提醒消息并发出蜂鸣声。

六、文件格式转换脚本

在日常工作中,我们可能需要将一种文件格式转换为另一种格式。例如,将图片从 JPEG 格式转换为 PNG 格式,或者将 PDF 文件转换为 Word 文档。以下是一个使用 Python 的第三方库 Pillow 进行图片格式转换的脚本:

from PIL import Imagedef convert_image_format(input_path, output_path, output_format):img = Image.open(input_path)img.save(output_path, format=output_format)input_path = "path/to/input/image.jpg"
output_path = "path/to/output/image.png"
output_format = "PNG"
convert_image_format(input_path, output_path, output_format)

这个脚本可以将指定的 JPEG 图片转换为 PNG 格式。你可以根据需要修改输入路径、输出路径和输出格式。

七、批量压缩图片脚本

当我们有大量的图片需要压缩以减小文件大小或节省存储空间时,可以使用以下脚本:

from PIL import Image
import osdef compress_images(directory, quality):for filename in os.listdir(directory):if filename.endswith(".jpg") or filename.endswith(".png"):img_path = os.path.join(directory, filename)img = Image.open(img_path)img.save(img_path, optimize=True, quality=quality)directory = "path/to/your/images/directory"
quality = 70  # 设置压缩质量,范围为 0-100
compress_images(directory, quality)

这个脚本遍历指定目录中的所有 JPEG 和 PNG 图片,并将它们压缩到指定的质量级别。

八、生成随机密码脚本

为了提高账户安全性,我们经常需要使用随机生成的强密码。以下是一个用 Python 生成随机密码的脚本:

import random
import stringdef generate_password(length):characters = string.ascii_letters + string.digits + string.punctuationpassword = ''.join(random.choice(characters) for i in range(length))return passwordlength = 12  # 设置密码长度
password = generate_password(length)
print(password)

这个脚本生成一个指定长度的随机密码,包含字母、数字和标点符号。

九、清理临时文件脚本

电脑中的临时文件会占用存储空间并可能影响系统性能。以下是一个清理特定目录中临时文件的脚本:

import osdef clean_temp_files(directory):for filename in os.listdir(directory):file_path = os.path.join(directory, filename)if os.path.isfile(file_path) and filename.startswith("temp_"):os.remove(file_path)directory = "path/to/temporary/files/directory"
clean_temp_files(directory)

这个脚本删除指定目录中以 “temp_” 开头的临时文件。

十、文本内容搜索与替换脚本

如果你需要在多个文本文件中搜索特定的内容并进行替换,可以使用以下脚本:

import osdef search_and_replace(directory, search_text, replace_text):for filename in os.listdir(directory):if filename.endswith(".txt"):file_path = os.path.join(directory, filename)with open(file_path, "r") as file:content = file.read()new_content = content.replace(search_text, replace_text)with open(file_path, "w") as file:file.write(new_content)directory = "path/to/your/text/files/directory"
search_text = "old_text"
replace_text = "new_text"
search_and_replace(directory, search_text, replace_text)

这个脚本遍历指定目录中的所有文本文件,将文件中的特定内容替换为新的内容。

十一、获取网页内容脚本

有时候我们需要从网页上获取特定的信息,比如新闻标题、股票价格等。以下是一个使用 Python 的 requests 和 BeautifulSoup 库获取网页内容的脚本:

import requests
from bs4 import BeautifulSoupdef get_webpage_content(url):response = requests.get(url)soup = BeautifulSoup(response.content, "html.parser")# 假设我们要获取网页中的所有标题标签titles = soup.find_all("h1")for title in titles:print(title.text)url = "https://example.com"
get_webpage_content(url)

这个脚本获取指定网页的内容,并打印出所有的一级标题。

十二、文件分类脚本

如果你的电脑中有很多杂乱无章的文件,可以使用以下脚本进行分类:

import os
import shutildef classify_files(directory):file_types = {}for filename in os.listdir(directory):file_path = os.path.join(directory, filename)if os.path.isfile(file_path):extension = os.path.splitext(filename)[1]if extension not in file_types:file_types[extension] = []file_types[extension].append(file_path)for extension, files in file_types.items():destination_folder = os.path.join(directory, extension[1:])os.makedirs(destination_folder, exist_ok=True)for file in files:shutil.move(file, destination_folder)directory = "path/to/your/files/directory"
classify_files(directory)

这个脚本根据文件的扩展名将文件分类到不同的文件夹中。

十三、总结

这些 Python 小脚本可以在日常办公和电脑管理中发挥很大的作用。它们不仅可以提高工作效率,还可以帮助我们更好地管理电脑资源和处理各种任务。你可以根据自己的具体需求对这些脚本进行修改和扩展,以满足不同的场景。同时,不断探索和学习更多的 Python 库和技术,可以让你编写出更加实用和强大的脚本。


http://www.ppmy.cn/devtools/128207.html

相关文章

jar 导入本地和远程私服 maven 仓库

jar 导入本地和远程私服 maven 仓库artemis-http-client 认证库 maven 坐标为: 执行 mvn 命令: mvn install:install-file -DfileD:\download\lib\artemis-http-client-1.1.12.RELEASE.jar -DgroupIdcom.hikvision.ga -DartifactIdartemis-http-clien…

C++编程:实现一个基于原始指针的环形缓冲区(RingBuffer)缓存串口数据

文章目录 0. 引言1. 使用示例2. 流程图2.1 追加数据流程2.2 获取空闲块流程2.3 处理特殊字符流程2.4 释放块流程2.5 获取下一个使用块流程 3. 代码详解3.1 Block 结构体3.2 RingBuffer 类3.3 主要方法解析append 方法currentUsed 和 currentUsing 方法release 方法nextUsed 方法…

SQLI LABS | Less-3 GET-Error based-Single quotes with twist-String

关注这个靶场的其它相关笔记:SQLI LABS —— 靶场笔记合集-CSDN博客 0x01:过关流程 输入下面的链接进入靶场(如果你的地址和我不一样,按照你本地的环境来): http://localhost/sqli-labs/Less-3/ 靶场提示 …

React(五) 受控组件和非受控组件; 获取表单元素的值。高阶组件(重点),Portals; Fragment组件;严格模式StrictMode

文章目录 一、受控组件1. 什么是受控组件2. 收集input框内容3. 收集checkBox的值4. 下拉框select总结 二、非受控组件三、高阶组件1. 高阶组件的概念 (回顾高阶函数)2. 高阶组件应用:注入props(1) 高阶组件给---函数式组件注入props(2) 高阶组件给---类组件注入prop…

.net framework 3.5sp1安装错误怎样解决?

.net framework 3.5sp1安装错误怎样解决? 解决.NETFramework3.5SP1安装错误的方法通常包括以下几个步骤: 1.确保系统更新:首先,确保你的Windows系统是最新的。可以通过WindowsUpdate检查更新。 2.使用DISM工具:使用…

思科网络设备命令

一、交换机巡检命令 接口和流量状态 show interface stats:查看所有接口当前流量。show interface summary:查看所有接口当前状态和流量。show interface status:查看接口状态及可能的错误。show interface | include errors | FastEthernet …

Sentinel 介绍

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开…

幼儿和青少年编程学习路径

1. 引言 编程在现代教育中的重要性 随着信息时代的来临,编程不再是一个小众技能,而是成为未来社会各行业的重要基础能力。从计算机科学到人工智能,再到数据科学和软件工程,编程技能无疑是未来全球经济的核心驱动力之一。越来越多…