python-script-library/战神修改文件名.py

84 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
fix_commas_and_pad_multi.py
批量修复多个文件夹中含逗号的数字文件名并补齐到6位例如:
"01,000.png" -> "001000.png"
支持扫描指定文件夹中所有以"25"开头的子文件夹
"""
import os
import argparse
VALID_EXTS = {'.png', '.exr'}
def safe_rename(src, dst, dry_run=False):
if os.path.exists(dst):
print(f"[跳过] 目标已存在,未重命名:{os.path.basename(src)} -> {os.path.basename(dst)}")
return False
print(f"[重命名] {os.path.basename(src)} -> {os.path.basename(dst)}")
if not dry_run:
os.rename(src, dst)
return True
def fix_folder(root_folder, dry_run=False):
changed = 0
for root, dirs, files in os.walk(root_folder):
for fname in files:
name, ext = os.path.splitext(fname)
if ext.lower() not in VALID_EXTS:
continue
# 若文件名中含逗号,则移除逗号
if ',' in name:
candidate = name.replace(',', '')
else:
candidate = None
if candidate is None or not candidate.isdigit():
continue
padded = candidate.zfill(6)
if padded == name:
continue
src_path = os.path.join(root, fname)
dst_path = os.path.join(root, padded + ext)
if safe_rename(src_path, dst_path, dry_run=dry_run):
changed += 1
print(f"[完成] {root_folder} 共重命名 {changed} 个文件。\n")
def find_25_folders(root_folder):
"""查找所有以'25'开头的子文件夹"""
folders = []
for item in os.listdir(root_folder):
item_path = os.path.join(root_folder, item)
if os.path.isdir(item_path) and item.startswith('25'):
folders.append(item_path)
return folders
def main():
p = argparse.ArgumentParser(
description="修复含逗号的数字文件名并补齐到6位例如 01,000.png -> 001000.png扫描指定文件夹中所有以25开头的子文件夹"
)
p.add_argument("root_folder", help="包含多个以25开头的子文件夹的根目录")
p.add_argument("--dry-run", action="store_true", help="仅模拟显示将要做的重命名,不执行")
args = p.parse_args()
if not os.path.isdir(args.root_folder):
print(f"❌ 路径无效:{args.root_folder}")
return
target_folders = find_25_folders(args.root_folder)
if not target_folders:
print(f"❌ 在 {args.root_folder} 中未找到以'25'开头的子文件夹")
return
print(f"\n=== 在 {args.root_folder} 中找到 {len(target_folders)} 个以'25'开头的子文件夹 ===")
for folder in target_folders:
print(f"\n=== 处理文件夹:{folder} ===")
fix_folder(folder, dry_run=args.dry_run)
if __name__ == "__main__":
main()