我想根据根名称作为目录名来重命名图片列表(本例中的图片),根据文件总数和增量,用适当的零填充前面的编号。我在考虑使用Powershell或Python。推荐?
当前的“C:\picture”目录内容
pic 1.jpg
...
pic 101.jpg结果
picture 001.jpg
...
picture 101.jpg发布于 2013-10-08 11:26:20
以下是python的解决方案:
import glob
import os
dirpath = r'c:\picture'
dirname = os.path.basename(dirpath)
filepath_list = glob.glob(os.path.join(dirpath, 'pic *.jpg'))
pad = len(str(len(filepath_list)))
for n, filepath in enumerate(filepath_list, 1):
os.rename(
filepath,
os.path.join(dirpath, 'picture {:>0{}}.jpg'.format(n, pad))
)pad是使用文件数计算的,如果文件数是100,则len(filepath_list)len(str(100)) # 3'picture {:>0{}}.jpg'.format(99, 3)类似于'picture {:>03}.jpg'.format(99)。格式字符串{:>03}补零(0),右对齐(>)输入值(99 in the example).'picture {:>0{}}.jpg'.format(99,3)‘099.jpg' 099.jpg’>‘99 {:>03}.jpg'.format(99)’图片格式
所用函数的文档:
发布于 2013-10-08 11:37:28
假设
您已经知道如何遍历脚本中的文件名并重命名directory
需要理解的几件事
str.format提供了一个精心设计的格式字符串说明符来实现此演示
>>> no_of_files = 100
>>> no_of_digits = int(math.log10(no_of_files)) + 1
>>> format_exp = "pictures {{:>0{}}}.{{}}".format(no_of_digits)
>>> for fname in files:
#Discard the irrelevant portion
fname = fname.rsplit()[-1]
print format_exp.format(*fname.split('.'))
pictures 001.jpg
pictures 002.jpg
pictures 010.jpg
pictures 100.jpg发布于 2013-10-08 12:08:04
这是一个PowerShell解决方案:
$jpgs = Get-ChildItem C:\Picture\*.jpg
$numDigits = "$($jpgs.Length)".Length
$formatStr = "{0:$('0' * $numDigits)}"
$jpgs | Where {$_.BaseName -match '(\d+)'} |
Rename-Item -NewName {$_.DirectoryName + '\' + $_.Directory.Name + ($formatStr -f [int]$matches[1]) + $_.Extension} -WhatIf如果使用-WhatIf获得的预览效果良好,请删除-WhatIf参数以实际执行重命名。
https://stackoverflow.com/questions/19238513
复制相似问题