本文目录导读:

Windows Batch 脚本 (.bat)
单个扩展名替换
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
echo ========================================
echo 批量修改文件扩展名工具
echo ========================================
:: 设置要修改的文件夹路径(默认当前文件夹)
set /p "folder=请输入文件夹路径(直接回车使用当前文件夹): "
if "%folder%"=="" set "folder=%cd%"
:: 设置原始扩展名和新扩展名
set /p "old_ext=请输入原始扩展名(如 txt): "
set /p "new_ext=请输入新扩展名(如 doc): "
cd /d "%folder%"
echo.
echo 正在处理文件...
set count=0
for %%f in (*.%old_ext%) do (
ren "%%f" "%%~nf.%new_ext%"
set /a count+=1
echo 已修改: %%f -^> %%~nf.%new_ext%
)
echo.
echo 共修改了 %count% 个文件
pause
批量处理多个扩展名
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
echo ========================================
echo 批量修改多个扩展名
echo ========================================
set /p "folder=请输入文件夹路径(回车使用当前): "
if "%folder%"=="" set "folder=%cd%"
cd /d "%folder%"
echo 正在转换文件...
:: 转换示例:.jpeg 改为 .jpg
set count=0
for %%f in (*.jpeg) do (
ren "%%f" "%%~nf.jpg"
set /a count+=1
)
echo JPEG 转 JPG: %count% 个文件
:: 转换示例:.txt 改为 .md
set count=0
for %%f in (*.txt) do (
ren "%%f" "%%~nf.md"
set /a count+=1
)
echo TXT 转 MD: %count% 个文件
echo.
echo 操作完成!
pause
PowerShell 脚本 (.ps1)
# 批量修改文件扩展名脚本
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " 批量修改文件扩展名工具" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# 获取文件夹路径
$folder = Read-Host "请输入文件夹路径(直接回车使用当前文件夹)"
if ([string]::IsNullOrEmpty($folder)) {
$folder = Get-Location
}
# 设置扩展名
$oldExt = Read-Host "请输入原始扩展名(不含点,如 txt)"
$newExt = Read-Host "请输入新扩展名(不含点,如 doc)"
# 检查文件夹是否存在
if (-not (Test-Path $folder)) {
Write-Host "文件夹不存在!" -ForegroundColor Red
exit
}
# 获取文件列表
$files = Get-ChildItem -Path $folder -Filter "*.$oldExt" -File
$count = 0
Write-Host "`n正在处理文件..." -ForegroundColor Yellow
foreach ($file in $files) {
$newName = $file.BaseName + "." + $newExt
Rename-Item -Path $file.FullName -NewName $newName
$count++
Write-Host "已修改: $($file.Name) -> $newName" -ForegroundColor Green
}
Write-Host "`n共修改了 $count 个文件" -ForegroundColor Cyan
Write-Host ""
Write-Host "按任意键退出..." -ForegroundColor Gray
Read-Host
Python 脚本 (.py)
import os
import sys
from pathlib import Path
def batch_rename_extension(folder_path, old_ext, new_ext):
"""
批量修改文件扩展名
Args:
folder_path: 文件夹路径
old_ext: 原始扩展名(不含点)
new_ext: 新扩展名(不含点)
"""
# 确保扩展名没有点
old_ext = old_ext.lstrip('.')
new_ext = new_ext.lstrip('.')
# 检查文件夹是否存在
if not os.path.exists(folder_path):
print(f"错误:文件夹 {folder_path} 不存在!")
return 0
# 遍历文件夹中的文件
count = 0
for filename in os.listdir(folder_path):
# 检查文件是否匹配原始扩展名
if filename.lower().endswith(f'.{old_ext.lower()}'):
old_path = os.path.join(folder_path, filename)
# 如果是文件而不是文件夹
if os.path.isfile(old_path):
# 构建新文件名
name_without_ext = os.path.splitext(filename)[0]
new_filename = f"{name_without_ext}.{new_ext}"
new_path = os.path.join(folder_path, new_filename)
# 重命名文件
try:
os.rename(old_path, new_path)
print(f"已修改: {filename} -> {new_filename}")
count += 1
except Exception as e:
print(f"修改失败: {filename} - 错误: {e}")
return count
def main():
print("=" * 40)
print("批量修改文件扩展名工具")
print("=" * 40)
# 获取用户输入
folder = input("请输入文件夹路径(直接回车使用当前文件夹): ").strip()
if not folder:
folder = os.getcwd()
old_ext = input("请输入原始扩展名(如 txt): ").strip()
new_ext = input("请输入新扩展名(如 doc): ").strip()
# 执行批量修改
count = batch_rename_extension(folder, old_ext, new_ext)
print(f"\n共修改了 {count} 个文件")
input("\n按任意键退出...")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n操作已取消")
sys.exit(0)
Python 高级版(带错误处理和日志)
import os
import logging
from datetime import datetime
from pathlib import Path
class ExtensionRenamer:
def __init__(self):
self.setup_logging()
def setup_logging(self):
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('rename_log.txt', 'a', encoding='utf-8')
]
)
self.logger = logging.getLogger(__name__)
def rename_files(self, folder_path, old_ext, new_ext, recursive=True):
"""批量修改文件扩展名,支持递归"""
old_ext = old_ext.lstrip('.').lower()
new_ext = new_ext.lstrip('.').lower()
# 生成时间戳备份文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = f"rename_history_{timestamp}.txt"
renamed_count = 0
error_count = 0
history = []
# 获取所有文件(支持递归)
pattern = f"*.{old_ext}"
if recursive:
files = Path(folder_path).rglob(pattern)
else:
files = Path(folder_path).glob(pattern)
for file_path in files:
if not file_path.is_file():
continue
new_path = file_path.with_suffix(f".{new_ext}")
# 记录历史
history.append(f"{file_path} -> {new_path}")
try:
if new_path.exists():
raise FileExistsError("目标文件已存在")
file_path.rename(new_path)
renamed_count += 1
self.logger.info(f"成功: {file_path.name} -> {new_path.name}")
except Exception as e:
error_count += 1
self.logger.error(f"失败: {file_path.name} - {str(e)}")
# 保存重命名历史
self.save_history(history, backup_file)
# 返回统计信息
return {
'renamed': renamed_count,
'errors': error_count,
'total': renamed_count + error_count,
'backup_file': backup_file
}
def save_history(self, history, backup_file):
"""保存重命名历史记录"""
try:
with open(backup_file, 'w', encoding='utf-8') as f:
f.write("文件重命名历史记录\n")
f.write("=" * 50 + "\n")
f.write(f"日期: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("=" * 50 + "\n\n")
for item in history:
f.write(item + "\n")
self.logger.info(f"历史记录已保存至: {backup_file}")
except Exception as e:
self.logger.error(f"保存历史记录失败: {str(e)}")
def interactive_mode(self):
"""交互模式"""
print("=" * 50)
print(" 批量修改文件扩展名 - 高级版")
print("=" * 50)
folder = input("请输入文件夹路径(回车使用当前目录): ").strip()
if not folder:
folder = os.getcwd()
old_ext = input("请输入原始扩展名(如 txt): ").strip()
if not old_ext:
print("错误:请输入原始扩展名")
return
new_ext = input("请输入新扩展名(如 doc): ").strip()
if not new_ext:
print("错误:请输入新扩展名")
return
recursive = input("是否递归处理子文件夹?(y/n,默认y): ").strip().lower()
recursive = recursive != 'n'
print(f"\n开始处理...")
print(f"文件夹: {folder}")
print(f"转换: *.{old_ext} -> *.{new_ext}")
print(f"递归处理: {'是' if recursive else '否'}")
print("-" * 50)
result = self.rename_files(folder, old_ext, new_ext, recursive)
print("-" * 50)
print(f"处理完成!")
print(f"成功: {result['renamed']} 个文件")
print(f"失败: {result['errors']} 个文件")
print(f"总计: {result['total']} 个文件")
print(f"历史记录: {result['backup_file']}")
if __name__ == "__main__":
renamer = ExtensionRenamer()
renamer.interactive_mode()
使用方法:
Windows
- 在文件夹中新建文本文件,粘贴代码,保存为
.bat或.ps1文件 - 双击运行,按提示输入参数
Python
- 保存为
.py文件,运行python rename_extensions.py - 或直接修改代码中的参数
注意事项:
- 备份重要文件:建议在操作前备份文件
- 确认目标文件名:避免覆盖现有文件
- 测试运行:先在少量文件上测试
- 权限问题:确保有权限修改文件
选择最适合你需求的脚本即可!