按要求将CAAU7083393 TE-WB1215 1-10843 0T 19.02.2025.pdf这类文件名批量替换为TE-WB1215 CAAU7083393 1-10843 0T 19.02.2025.pdf
pythonimport os
import re
from datetime import datetime
def validate_container_number(container):
return re.match(r'^[A-Za-z]{4}\d{7}$', container) is not None
def validate_tewb_code(tewb):
return re.match(r'^\w{1,}-WB\d{4}$', tewb, re.IGNORECASE) is not None
def validate_date(date_str):
try:
datetime.strptime(date_str, "%d.%m.%Y")
return True
except ValueError:
return False
def rename_pdf_files(directory, dry_run=True):
"""
批量重命名PDF文件
:param directory: 目标目录路径
:param dry_run: 模拟运行模式(True只显示预览,False实际执行)
"""
pattern = re.compile(
r'^'
r'(?P<container>[A-Za-z]{4}\d{7}) '
r'(?P<tewb>\w{1,}-WB\d{4}) '
r'(?P<content>.+?) '
r'(?P<date>\d{2}\.\d{2}\.\d{4})'
r'\.pdf$',
re.IGNORECASE
)
for filename in sorted(os.listdir(directory)):
if not filename.lower().endswith('.pdf'):
continue
match = pattern.match(filename)
if not match:
print(f"格式不匹配,跳过文件: {filename}")
continue
groups = match.groupdict()
validation = (
(validate_container_number(groups['container']), "集装箱号格式错误"),
(validate_tewb_code(groups['tewb']), "WB代码格式错误"),
(validate_date(groups['date']), "日期格式错误")
)
if not all(v[0] for v in validation):
errors = ", ".join([v[1] for v in validation if not v[0]])
print(f"验证失败:{filename} -> {errors}")
continue
new_name = f"{groups['tewb']} {groups['container']} {groups['content']} {groups['date']}.pdf"
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_name)
if dry_run:
print(f"[模拟模式] 将重命名: {filename} -> {new_name}")
else:
try:
os.rename(old_path, new_path)
print(f"成功重命名: {filename} -> {new_name}")
except Exception as e:
print(f"重命名失败: {filename} | 错误: {str(e)}")
if __name__ == "__main__":
target_dir = os.getcwd()
# 第一次先运行模拟模式(不实际修改文件)
print("=== 模拟运行 ===")
rename_pdf_files(target_dir, dry_run=True)
# 确认无误后,注释下面两行并取消注释最后一行
# confirm = input("\n确认要执行重命名吗?(y/n): ")
# if confirm.lower() == 'y':
# rename_pdf_files(target_dir, dry_run=False)
本文作者:ivan
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!