今天给大家分享20个 python 日常使用最频繁的自动化脚本。
1、文件批量重命名脚本:
import os
def batch_rename_files(folder_path, old_extension, new_extension):
for file in os.listdir(folder_path):
if file.endswith(old_extension):
old_file_path = os.path.join(folder_path, file)
new_file_name = file[:-len(old_extension)] + new_extension
new_file_path = os.path.join(folder_path, new_file_name)
os.rename(old_file_path, new_file_path)
# 示例用法
batch_rename_files('/your/folder', '.txt', '.log')
此脚本可将指定文件夹内特定扩展名的文件批量修改为新的扩展名。
2、数据备份脚本(以复制文件夹为例):
import shutil
def backup_folder(source_folder, destination_folder):
shutil.copytree(source_folder, destination_folder)
# 示例用法
backup_folder('/source/dir', '/backup/dir')
用于将一个文件夹完整备份到另一个位置。
3、自动化邮件发送脚本:
import smtplib
from email.mime.text import MIMEText
def send_email(sender_email, sender_password, receiver_email, subject, message):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
# 示例用法
send_email('your_email@gmail.com', 'your_password', 'recipient@example.com', 'Test Email', 'This is a test.')
可在程序中自动发送邮件。
4、图片格式转换脚本:
from PIL import Image
def convert_image_format(image_path, new_format):
image = Image.open(image_path)
new_image_path = image_path[:-4] + new_format
image.save(new_image_path)
# 示例用法
convert_image_format('/your/image.jpg', '.png')
将指定图片转换为新的格式。
5、文本文件合并脚本:
def merge_text_files(folder_path, output_file):
with open(output_file, 'w') as outfile:
for file in os.listdir(folder_path):
if file.endswith('.txt'):
with open(os.path.join(folder_path, file), 'r') as infile:
outfile.write(infile.read())
# 示例用法
merge_text_files('/text/files/folder', 'combined.txt')
将一个文件夹内的所有文本文件内容合并到一个新文件。
6、系统资源监控脚本(简单的 CPU 使用率监控):
import psutil
defmonitor_cpu_usage():
cpu_usage = psutil.cpu_percent(interval=1)
print(f"CPU Usage: {cpu_usage}%")
# 示例用法
monitor_cpu_usage()
实时获取当前 CPU 使用率。
7、自动化数据采集脚本(以抓取网页标题为例):
import requests
from bs4 import BeautifulSoup
def scrape_webpage_titles(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
titles = [title.text for title in soup.find_all('h1')]
return titles
# 示例用法
titles = scrape_webpage_titles('https://yourwebsite.com')
print(titles)
从指定网页抓取标题信息。
8、批量创建文件夹脚本:
import os
defcreate_folders(prefix, num_folders):
for i inrange(num_folders):
folder_name = prefix + str(i)
os.makedirs(folder_name)
# 示例用法
create_folders('new_folder_', 5)
根据指定前缀批量创建多个文件夹。
9、自动化数据清理脚本(去除列表中的重复元素):
defclean_data(data_list):
returnlist(set(data_list))
# 示例用法
data = [1, 2, 2, 3, 3, 4]
cleaned_data = clean_data(data)
print(cleaned_data)
对数据列表进行去重处理。
10、定时任务执行脚本(简单的定时打印示例):
import schedule
import time
def print_message():
print("This is a scheduled message.")
schedule.every(5).minutes.do(print_message)
while True:
schedule.run_pending()
time.sleep(1)
设置每隔 5 分钟执行一次打印任务。
11、自动化文件搜索脚本:
import os
def search_files(keyword, root_dir):
result = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if keyword in file:
file_path = os.path.join(root, file)
result.append(file_path)
return result
# 示例用法
found_files = search_files('report', '/your/directory')
print(found_files)
在指定目录及其子目录下搜索包含特定关键词的文件。
12、数据库数据导出脚本(以 MySQL 为例):
import subprocess
defexport_mysql_data(database, user, password, output_file):
command = f'mysqldump -u {user} -p{password}{database} > {output_file}'
subprocess.call(command, shell=True)
# 示例用法
export_mysql_data('your_database', 'your_user', 'your_password', 'data_dump.sql')
将 MySQL 数据库中的数据导出到指定的 SQL 文件。
13、自动化软件安装脚本(以安装特定 Python 库为例):
import subprocess
definstall_package(package_name):
subprocess.call(['pip', 'install', package_name])
# 示例用法
install_package('numpy')
使用 pip 自动安装指定的 Python 包。
14、图像裁剪脚本:
from PIL import Image
def crop_image(image_path, left, top, right, bottom):
image = Image.open(image_path)
cropped_image = image.crop((left, top, right, bottom))
cropped_image.save('cropped_' + image_path)
# 示例用法
crop_image('/your/image.jpg', 100, 100, 400, 400)
对图像进行裁剪操作并保存。
15、文本替换脚本(在文本文件中替换特定字符串):
def replace_text_in_file(file_path, old_text, new_text):
with open(file_path, 'r+') as file:
content = file.read()
new_content = content.replace(old_text, new_text)
file.seek(0)
file.write(new_content)
file.truncate()
# 示例用法
replace_text_in_file('/your/text.txt', 'old_word', 'new_word')
在指定文本文件中替换特定的字符串。
16、网络连接测试脚本:
import socket
deftest_network_connection(host, port):
try:
socket.create_connection((host, port), timeout=5)
print(f"Connection to {host}:{port} successful.")
except (socket.timeout, ConnectionRefusedError):
print(f"Connection to {host}:{port} failed.")
# 示例用法
test_network_connection('www.google.com', 80)
测试与指定主机和端口的网络连接是否成功。
17、音频文件播放脚本(使用 playsound 库):
from playsound import playsound
defplay_audio_file(audio_path):
playsound(audio_path)
# 示例用法
play_audio_file('/your/audio.mp3')
播放指定的音频文件。
18、视频文件信息提取脚本(使用 moviepy 库获取时长等信息):
from moviepy.editor import VideoFileClip
defget_video_info(video_path):
video = VideoFileClip(video_path)
print(f"Duration: {video.duration} seconds")
print(f"Size: {os.path.getsize(video_path)} bytes")
video.close()
# 示例用法
get_video_info('/your/video.mp4')
提取视频文件的时长和大小等信息。
19、自动化生成随机密码脚本:
import random
importstring
def generate_random_password(length):
all_characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(all_characters) for i in range(length))
return password
# 示例用法
password = generate_random_password(10)
print(password)
生成指定长度的随机密码。
20、系统日志分析脚本(简单示例,统计特定关键词出现次数):
def analyze_log_file(log_path, keyword):
count = 0
withopen(log_path, 'r') as log:
for line in log.readlines():
if keyword in line:
count += 1
return count
# 示例用法
occurrences = analyze_log_file('/your/log.log', 'error')
print(f"Keyword 'error' appears {occurrences} times.")
分析系统日志文件中特定关键词的出现次数。