上一篇
Python脚本教程:常见脚本类型与实用示例 - Python编程指南
- Python
- 2025-07-23
- 796
Python脚本教程:常见脚本类型与实用示例
Python因其简洁语法和强大功能成为最流行的脚本语言之一。本教程介绍常见Python脚本类型并提供实用示例。
一、文件处理脚本
Python非常适合处理文件和目录操作,包括读写文件、批量重命名、日志分析等。
1. 批量重命名文件
以下脚本将目录中所有.txt文件重命名为new_001.txt、new_002.txt等格式:
import os
def batch_rename(directory, prefix):
"""批量重命名目录中的文件"""
files = [f for f in os.listdir(directory) if f.endswith('.txt')]
files.sort()
for count, filename in enumerate(files):
new_name = f"{prefix}_{count+1:03d}.txt"
src = os.path.join(directory, filename)
dst = os.path.join(directory, new_name)
os.rename(src, dst)
print(f"重命名: {filename} -> {new_name}")
# 使用示例
batch_rename("/path/to/your/files", "new")
2. 日志文件分析
分析服务器日志,统计错误出现次数:
def analyze_logs(log_file_path, error_keyword="ERROR"):
"""统计日志文件中特定错误的出现次数"""
error_count = 0
with open(log_file_path, 'r') as file:
for line in file:
if error_keyword in line:
error_count += 1
print(f"在日志文件中发现 {error_count} 个'{error_keyword}'错误")
return error_count
# 使用示例
analyze_logs("/var/log/app.log")
二、网络爬虫脚本
使用Python抓取网页数据是常见应用场景。
简单网页爬虫
使用requests和BeautifulSoup抓取网页标题和链接:
import requests
from bs4 import BeautifulSoup
def simple_crawler(url):
"""获取网页标题和所有链接"""
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# 获取页面标题
title = soup.title.string if soup.title else "无标题"
print(f"页面标题: {title}")
# 获取所有链接
links = []
for link in soup.find_all('a', href=True):
href = link['href']
if href.startswith('http'):
links.append(href)
print(f"发现 {len(links)} 个有效链接")
return links
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")
return []
# 使用示例
simple_crawler("https://example.com")
三、数据分析脚本
Python在数据科学领域有强大工具支持。
CSV数据分析
使用pandas分析销售数据:
import pandas as pd
def analyze_sales_data(csv_path):
"""分析销售数据CSV文件"""
# 读取CSV数据
df = pd.read_csv(csv_path)
# 基本统计
total_sales = df['销售额'].sum()
average_sale = df['销售额'].mean()
best_product = df.groupby('产品')['销售额'].sum().idxmax()
print(f"总销售额: ¥{total_sales:,.2f}")
print(f"平均每单销售额: ¥{average_sale:,.2f}")
print(f"最畅销产品: {best_product}")
# 返回结果
return {
'total_sales': total_sales,
'average_sale': average_sale,
'best_product': best_product
}
# 使用示例
analyze_sales_data("sales_data.csv")
四、系统自动化脚本
Python可以自动化日常重复性任务。
1. 自动文件备份
创建重要文件的压缩备份:
import os
import shutil
from datetime import datetime
def auto_backup(source_dir, dest_dir):
"""创建源目录的带时间戳的压缩备份"""
if not os.path.exists(source_dir):
print(f"错误: 源目录不存在 {source_dir}")
return
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
# 创建时间戳
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"backup_{timestamp}.zip"
backup_path = os.path.join(dest_dir, backup_name)
# 创建压缩备份
shutil.make_archive(backup_path.replace('.zip', ''), 'zip', source_dir)
print(f"备份成功创建于: {backup_path}")
return backup_path
# 使用示例
auto_backup("/path/to/important/files", "/backup/destination")
2. 自动化测试脚本
使用unittest编写简单测试用例:
import unittest
def add_numbers(a, b):
"""两个数字相加"""
return a + b
class TestMathFunctions(unittest.TestCase):
"""测试数学函数"""
def test_add_positive(self):
self.assertEqual(add_numbers(2, 3), 5)
def test_add_negative(self):
self.assertEqual(add_numbers(-1, -1), -2)
def test_add_mixed(self):
self.assertEqual(add_numbers(5, -3), 2)
if __name__ == '__main__':
unittest.main()
五、实用工具脚本
1. 图片格式转换
使用PIL库批量转换图片格式:
from PIL import Image
import os
def convert_images(source_dir, dest_dir, new_format="JPEG"):
"""将目录中的图片转换为指定格式"""
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
# 支持的图片格式
valid_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']
for filename in os.listdir(source_dir):
if any(filename.lower().endswith(ext) for ext in valid_formats):
source_path = os.path.join(source_dir, filename)
dest_path = os.path.join(dest_dir, f"{os.path.splitext(filename)[0]}.{new_format.lower()}")
try:
with Image.open(source_path) as img:
img.save(dest_path, format=new_format)
print(f"转换成功: {filename} -> {os.path.basename(dest_path)}")
except Exception as e:
print(f"转换失败 {filename}: {str(e)}")
# 使用示例:将PNG转为JPG
convert_images("/path/to/pngs", "/path/to/jpgs", "JPEG")
2. 密码生成器
创建安全的随机密码:
import random
import string
def generate_password(length=12, use_digits=True, use_symbols=True):
"""生成随机密码"""
characters = string.ascii_letters
if use_digits:
characters += string.digits
if use_symbols:
characters += string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
# 生成示例密码
print("生成密码:", generate_password())
print("数字密码:", generate_password(8, True, False))
print("复杂密码:", generate_password(16, True, True))
总结
Python脚本可以应用于各种场景:
- 文件处理:自动化文件操作和管理
- 网络爬虫:数据采集和信息提取
- 数据分析:处理大型数据集和生成报告
- 系统自动化:定时任务和流程自动化
- 实用工具:开发小型实用程序解决特定问题
掌握Python脚本编写能显著提高工作效率,是每个开发者的必备技能。
本文由ZhuShuoKong于2025-07-23发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20256330.html
发表评论