[英]Batch Renaming of Files in a Directory Following a Specific Rule
有没有一种简单的方法可以使用Python以这种特定方式重命名目录中已经包含的文件?
我的目录中充满了像这样的图像
1 - imgA.jpg
2 - imgB.jpg
3 - imgC.jpg
我想将它们重命名为
3 - imgA.jpg
2 - imgB.jpg
1 - imgC.jpg
这应该可以解决问题:
>>> filenames = ['1 - imgA.jpg', '2 - imgB.jpg', '3 - imgC.jpg']
>>> filenames_split = [tuple(map(str.strip, f.split('-'))) for f in filenames]
>>> filenames_split
[('1', 'imgA.jpg'), ('2', 'imgB.jpg'), ('3', 'imgC.jpg')]
>>>
>>> n = len(filenames_split)
>>>
>>> filenames_split_new = [(str(n-int(number)+1), f) for number, f in filenames_split]
>>> filenames_split_new
[('3', 'imgA.jpg'), ('2', 'imgB.jpg'), ('1', 'imgC.jpg')]
>>> new_filenames = [' - '.join((number, f)) for number, f in filenames_split_new]
>>> new_filenames
['3 - imgA.jpg', '2 - imgB.jpg', '1 - imgC.jpg']
但是您必须先打开然后重新保存文件,对吗? 也许试试这个:
from PIL import Image
together = zip(filenames, new_filenames)
for f, new_f in together:
with Image.open(f) as opened_f:
opened_f.save(new_f)
或者您可以使用os.rename
,我不知道它存在:
together = zip(filenames, new_filenames)
for f, new_f in together:
os.rename(f, new_f)
我发现最简单的方法是在Excel(Office)VBA中编写一个小的例程,如下所示:
使用Command.Com中的Dir > CurrDirectory.Txt
(旧的DOS技巧:>符号将输出重定向到命名文件!
将CurrDirectory.Txt加载到Excel工作表中。 使用创建新文件名所需的任何代码。
使用以下步骤逐步浏览每个文件:
OldName =加载的旧名称NewName =新创建的名称
Name OldName As NewName
遍历所有需要的
您将需要使用模块“ re”和“ os”来实现:
import re, os
directory_name = "C:\\oneFolder\\"
rough_list = os.listdir(directory_name)
filtered_list = []
# filter the result to just files complying the pattern
for name in rough_list:
match = re.match("(\d+)( - img[A-Z]+.jpg)", name)
if match :
filtered_list.append([int(match.group(1)), match.group(0), match.group(2)])
# max num of digits
mx = len(str(max(filtered_list)[0]))
# create a list reversed indices
num = range(len(filtered_list), 0, -1)
# rename the files accordingly
for i,name in enumerate(sorted(filtered_list)):
os.rename(directory_name + name[1], directory_name + str(num[i]).zfill(mx) + name[2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.