Python 作为一种脚本语言,开发简单,几行代码却能发挥大作用。
本文将介绍几种有趣的 Python 脚本,一定能在你的生活和工作中发挥用处。
手动整理文件和文件夹可能很乏味。这个 Python 脚本可按扩展名类型自动将文件排序到文件夹中:
import os
import shutil
# Folder to organize
folder = '/path/to/folder/'
# File extensions and corresponding folder names
extensions = {
'Images': ['jpg', 'jpeg', 'png', 'svg'],
'Documents': ['doc', 'docx', 'pdf', 'xls', 'ppt', 'txt'],
'Video': ['mov', 'mp4', 'avi', 'wmv'],
'Audio': ['wav', 'mp3']
}
# Loop through items in folder
for item in os.listdir(folder):
filename, extension = os.path.splitext(item)
# If it's a file, move it to the corresponding folder
if extension:
for folder_name, ext_list in extensions.items():
if extension[1:] in ext_list:
folder_path = os.path.join(folder, folder_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
shutil.move(os.path.join(folder, item), folder_path)
如果你经常在网络上下载各种文件,比如视频,图片,文档等,那么你一定会感受到这个脚本的魅力,文件整理将不再头疼。
累积的旧文件会占用硬盘空间。该脚本可删除超过指定时间的文件,当然是要保证旧文件的确没用的前提下:
import os
import shutil
import datetime
# Folder to clean up
folder = '/path/to/folder'
# Files modified before this date will be deleted
days = 30
seconds = days * 24 * 60 * 60
min_date = datetime.datetime.now() - datetime.timedelta(seconds=seconds)
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
modified = os.path.getmtime(file_path)
if modified < min_date.timestamp():
print(f'Deleting old file: {file_path}')
os.remove(file_path)
设置好天数后,运行即可,运行前一定要保证旧文件不再使用。删除文件的脚本还是需要谨慎运行。
你也可以根据这个脚本举一反三,开发属于自己的文件删除/管理工具。
手动调整大量图片的大小非常耗时。该脚本可调整文件夹中所有图片的大小:
from PIL import Image
import os
# Folder containing images to resize
folder = '/path/to/folder'
# Desired image dimensions
size = (800, 600)
for img in os.listdir(folder):
if img.endswith(('jpg', 'jpeg', 'png')):
path = os.path.join(folder, img)
image = Image.open(path)
image_resized = image.resize(size)
image_resized.save(path)
print('Images resized successfully!')
只需设置所需的大小,然后运行即可轻松实现批量图像大小调整。
好吧,又是这个老生常谈的话题,密码生成工具。编写独特的密码是件麻烦事,本脚本可生成随机安全密码:
import random
import string
length = 12 # Password length
# List of characters to select from
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
# Combine all character sets
all = lower + upper + num + symbols
# Use random to create password
password = ''.join(random.sample(all,length))
print(password)
根据需要调整长度。这个脚本可以用来生成数据库密码或者 TOKEN 之类的字符串密码,如果拿来作为自己的账号密码,我建议还是使用密码工具比较合适。
因为现在的密码工具基本都带有自动填写功能,Python 创建密码虽好,但是输入的时候苦的是自己。
我之前用密码生成工具生成了一个长度在 50 左右的密码,有一次换设备登录,好嘛一顿输入,中间还输错一个重新来。
收到垃圾邮件很烦人。本脚本可将您从文本文件中的所有邮件列表退订:
import smtplib
from email.mime.text import MIMEText
# List of emails to unsubscribe from
unsub_emails = open('unsub_list.txt').readlines()
for email in unsub_emails:
msg = MIMEText('Unsubscribe')
msg['Subject'] = 'Unsubscribe'
msg['From'] = '[email protected]'
msg['To'] = email
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
print(f'Unsubscribed from {email}')
只需将邮件列表中的电子邮件放入 unsub_list.txt 即可运行。终于可以和垃圾邮件说再见了!
为图片添加水印可保护您的作品。该脚本可为文件夹中的所有图片添加水印:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img_folder = '/path/to/folder'
watermark_text = 'WaterMark'
# Load font
font = ImageFont.truetype('arial.ttf', 50)
for img in os.listdir(img_folder):
if img.endswith(('.jpg','.jpeg')):
path = os.path.join(img_folder, img)
image = Image.open(path)
# Make image editable
drawing = ImageDraw.Draw(image)
# Get text size
text_size = drawing.textsize(watermark_text, font)
# Set position
position = image.size[0] - text_size[0], image.size[1] - text_size[1]
# Add watermark
drawing.text(position, watermark_text, (255,255,255), font=font)
# Save watermarked image
image.save(path)
print('Added watermarks to all images!')
自定义水印文本和字体样式/大小,满足你的水印需求。
有些网站会在工作时分散注意力。该脚本可在设定的时间内屏蔽网站:
import time
from datetime import datetime as dt
hosts_path = r"/etc/hosts"
redirect = "127.0.0.1"
# List of websites to block
websites = ["www.facebook.com","facebook.com"]
start_time = dt(2023, 11, 10, 8, 0, 0)
end_time = dt(2023, 11, 10, 16, 0, 0)
while True:
if start_time < dt.now() < end_time:
print("Working hours...")
with open(hosts_path, 'r+') as file:
content = file.read()
for site in websites:
if site not in content:
file.write(redirect + " " + site + "\n")
else:
print("Free time...")
with open(hosts_path, 'r+') as file:
content = file.readlines()
file.seek(0)
for line in content:
if not any(site in line for site in websites):
file.write(line)
file.truncate()
time.sleep(5)
在您设定的工作时间内,它可以屏蔽和解除屏蔽网站,让您心无旁骛地提高工作效率。原理就是修改 hosts 文件,让网站无法正常访问。
以上就是今天提到的 Python 几个比较实用且好玩的脚本工具了,可以直接拿来使用,也可以学习其中的原理和思路。