本文目录导读:

我来帮你创建一个图片批量排序工具,支持按文件大小和名称排序。
图片批量排序工具
Python脚本(功能最全)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片批量排序工具 - 支持按大小和名称排序
"""
import os
import shutil
from pathlib import Path
def sort_images_by_size(source_dir, target_dir=None, order='asc'):
"""
按文件大小排序图片
Args:
source_dir: 源文件夹路径
target_dir: 目标文件夹路径(默认为源文件夹下的sorted_by_size)
order: 'asc' 升序(小到大),'desc' 降序(大到小)
"""
source_path = Path(source_dir)
if not source_path.exists():
print(f"源文件夹不存在: {source_dir}")
return
if target_dir is None:
target_dir = source_path / "sorted_by_size"
else:
target_dir = Path(target_dir)
target_dir.mkdir(exist_ok=True)
# 支持的图片格式
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.ico'}
# 获取所有图片文件及其大小
images = []
for file in source_path.iterdir():
if file.is_file() and file.suffix.lower() in image_extensions:
size = file.stat().st_size
images.append((size, file.name, file))
# 排序
reverse = order == 'desc'
images.sort(key=lambda x: x[0], reverse=reverse)
print(f"找到 {len(images)} 张图片")
print(f"排序方式: {'降序' if reverse else '升序'}")
print("-" * 50)
# 复制或移动文件到目标文件夹
for i, (size, name, file) in enumerate(images, 1):
# 添加序号前缀
new_name = f"{i:04d}_{name}"
target_file = target_dir / new_name
# 复制文件(如需移动改为 shutil.move)
shutil.copy2(file, target_file)
size_str = format_file_size(size)
print(f"{i:3d}. {name[:30]:30s} | 大小: {size_str:>8s}")
print(f"\n已排序到: {target_dir}")
def sort_images_by_name(source_dir, target_dir=None, order='asc'):
"""
按文件名排序图片
Args:
source_dir: 源文件夹路径
target_dir: 目标文件夹路径
order: 'asc' 升序(A-Z),'desc' 降序(Z-A)
"""
source_path = Path(source_dir)
if not source_path.exists():
print(f"源文件夹不存在: {source_dir}")
return
if target_dir is None:
target_dir = source_path / "sorted_by_name"
else:
target_dir = Path(target_dir)
target_dir.mkdir(exist_ok=True)
# 支持的图片格式
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.ico'}
# 获取所有图片文件
images = []
for file in source_path.iterdir():
if file.is_file() and file.suffix.lower() in image_extensions:
images.append(file)
# 排序
reverse = order == 'desc'
images.sort(key=lambda x: x.name.lower(), reverse=reverse)
print(f"找到 {len(images)} 张图片")
print(f"排序方式: {'降序(Z-A)' if reverse else '升序(A-Z)'}")
print("-" * 50)
# 复制文件
for i, file in enumerate(images, 1):
new_name = f"{i:04d}_{file.name}"
target_file = target_dir / new_name
shutil.copy2(file, target_file)
print(f"{i:3d}. {file.name[:30]:30s}")
def sort_images_by_creation_date(source_dir, target_dir=None, order='asc'):
"""
按创建/修改日期排序图片
"""
source_path = Path(source_dir)
if not source_path.exists():
print(f"源文件夹不存在: {source_dir}")
return
if target_dir is None:
target_dir = source_path / "sorted_by_date"
else:
target_dir = Path(target_dir)
target_dir.mkdir(exist_ok=True)
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.ico'}
images = []
for file in source_path.iterdir():
if file.is_file() and file.suffix.lower() in image_extensions:
mtime = file.stat().st_mtime # 修改时间
ctime = file.stat().st_ctime # 创建时间
images.append((mtime, ctime, file.name, file))
reverse = order == 'desc'
images.sort(key=lambda x: x[0], reverse=reverse)
from datetime import datetime
print(f"找到 {len(images)} 张图片")
print(f"排序方式: {'最新优先' if reverse else '最旧优先'}")
print("-" * 50)
for i, (mtime, ctime, name, file) in enumerate(images, 1):
new_name = f"{i:04d}_{name}"
target_file = target_dir / new_name
shutil.copy2(file, target_file)
date_str = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M")
print(f"{i:3d}. {name[:25]:25s} | 日期: {date_str}")
def format_file_size(size_bytes):
"""格式化文件大小显示"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.1f} TB"
def show_menu():
"""显示菜单"""
print("\n" + "=" * 50)
print("图片批量排序工具")
print("=" * 50)
print("1. 按文件大小排序(小到大)")
print("2. 按文件大小排序(大到小)")
print("3. 按文件名排序(A-Z)")
print("4. 按文件名排序(Z-A)")
print("5. 按创建日期排序(旧到新)")
print("6. 按创建日期排序(新到旧)")
print("0. 退出")
print("=" * 50)
def main():
"""主函数"""
while True:
show_menu()
choice = input("\n请选择操作 (0-6): ").strip()
if choice == '0':
print("感谢使用,再见!")
break
source_dir = input("请输入源文件夹路径: ").strip()
if not source_dir:
print("路径不能为空!")
continue
target_dir = input("请输入目标文件夹路径(直接回车使用默认路径): ").strip()
if not target_dir:
target_dir = None
print()
if choice == '1':
sort_images_by_size(source_dir, target_dir, 'asc')
elif choice == '2':
sort_images_by_size(source_dir, target_dir, 'desc')
elif choice == '3':
sort_images_by_name(source_dir, target_dir, 'asc')
elif choice == '4':
sort_images_by_name(source_dir, target_dir, 'desc')
elif choice == '5':
sort_images_by_creation_date(source_dir, target_dir, 'asc')
elif choice == '6':
sort_images_by_creation_date(source_dir, target_dir, 'desc')
else:
print("无效选择,请重新输入!")
input("\n按回车键继续...")
if __name__ == "__main__":
main()
批量重命名脚本(简洁版)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片批量重命名排序 - 简单版
"""
import os
from pathlib import Path
import shutil
def batch_rename_sort(folder_path, sort_by='name', prefix="img_"):
"""
批量重命名排序图片
Args:
folder_path: 图片文件夹路径
sort_by: 'name' 按名称, 'size' 按大小, 'date' 按日期
prefix: 文件前缀
"""
folder = Path(folder_path)
if not folder.exists():
print(f"文件夹不存在: {folder_path}")
return
# 支持的图片格式
extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
# 获取所有图片文件
images = []
for file in folder.iterdir():
if file.is_file() and file.suffix.lower() in extensions:
images.append(file)
if not images:
print("未找到图片文件")
return
# 根据排序方式排序
if sort_by == 'name':
images.sort(key=lambda x: x.name.lower())
elif sort_by == 'size':
images.sort(key=lambda x: x.stat().st_size)
elif sort_by == 'date':
images.sort(key=lambda x: x.stat().st_mtime)
print(f"找到 {len(images)} 张图片,开始重命名...")
# 重命名文件
for i, file in enumerate(images, 1):
new_name = f"{prefix}{i:04d}{file.suffix}"
new_path = folder / new_name
# 如果新文件名已存在,先重命名
if new_path.exists():
temp_name = f"temp_{i}_{file.name}"
file.rename(folder / temp_name)
(folder / temp_name).rename(new_path)
else:
file.rename(new_path)
print(f"{file.name[:25]:25s} -> {new_name}")
# 使用示例
if __name__ == "__main__":
# 按名称排序
batch_rename_sort("your_image_folder", "name")
# 按大小排序
# batch_rename_sort("your_image_folder", "size")
# 按日期排序
# batch_rename_sort("your_image_folder", "date")
批处理文件(Windows)
@echo off
chcp 65001 >nul图片批量排序工具
:menu
cls
echo ================================================
echo 图片批量排序工具
echo ================================================
echo 1. 按名称排序并重命名
echo 2. 按大小排序并重命名
echo 3. 按日期排序并重命名
echo 4. 退出
echo ================================================
set /p choice=请输入选择 (1-4):
if "%choice%"=="1" goto sort_name
if "%choice%"=="2" goto sort_size
if "%choice%"=="3" goto sort_date
if "%choice%"=="4" exit
goto menu
:sort_name
set /p folder=请输入文件夹路径:
if not exist "%folder%" (
echo 文件夹不存在!
pause
goto menu
)
cd /d "%folder%"
set count=1
for /f "delims=" %%i in ('dir /b /on *.jpg *.jpeg *.png *.gif *.bmp *.webp 2^>nul') do (
if %count% lss 10 (
set "newname=image_000%count%%%~xi"
) else if %count% lss 100 (
set "newname=image_00%count%%%~xi"
) else if %count% lss 1000 (
set "newname=image_0%count%%%~xi"
) else (
set "newname=image_%count%%%~xi"
)
ren "%%i" "!newname!"
set /a count+=1
)
echo 完成!处理了 %count% 个文件
pause
goto menu
:sort_size
set /p folder=请输入文件夹路径:
if not exist "%folder%" (
echo 文件夹不存在!
pause
goto menu
)
cd /d "%folder%"
set count=1
for /f "delims=" %%i in ('dir /b /os *.jpg *.jpeg *.png *.gif *.bmp *.webp 2^>nul') do (
if %count% lss 10 (
set "newname=image_000%count%%%~xi"
) else if %count% lss 100 (
set "newname=image_00%count%%%~xi"
) else if %count% lss 1000 (
set "newname=image_0%count%%%~xi"
) else (
set "newname=image_%count%%%~xi"
)
ren "%%i" "!newname!"
set /a count+=1
)
echo 完成!处理了 %count% 个文件
pause
goto menu
:sort_date
set /p folder=请输入文件夹路径:
if not exist "%folder%" (
echo 文件夹不存在!
pause
goto menu
)
cd /d "%folder%"
set count=1
for /f "delims=" %%i in ('dir /b /ot *.jpg *.jpeg *.png *.gif *.bmp *.webp 2^>nul') do (
if %count% lss 10 (
set "newname=image_000%count%%%~xi"
) else if %count% lss 100 (
set "newname=image_00%count%%%~xi"
) else if %count% lss 1000 (
set "newname=image_0%count%%%~xi"
) else (
set "newname=image_%count%%%~xi"
)
ren "%%i" "!newname!"
set /a count+=1
)
echo 完成!处理了 %count% 个文件
pause
goto menu
使用说明
-
Python版本(推荐)- 功能最全面:
- 保存为
sort_images.py - 运行:
python sort_images.py - 支持按大小、名称、日期排序
- 可选择升序或降序
- 保存为
-
简洁版 - 直接重命名:
- 保存为
rename_images.py - 修改文件夹路径后直接运行
- 只进行重命名操作
- 保存为
-
Windows批处理 - 无需安装Python:
- 保存为
sort_images.bat - 双击运行
- 直接修改原文件名
- 保存为
特点
- ✅ 支持多种图片格式(jpg、png、gif、bmp、webp等)
- ✅ 保留原始文件(复制到新文件夹)
- ✅ 自动添加排序序号
- ✅ 显示排序进度和文件信息
- ✅ 支持自定义输出路径
需要其他功能或遇到问题,请告诉我!
标签: 按大小名称排序
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播