Python 以数字顺序重命名文件+;信件

Python 以数字顺序重命名文件+;信件,python,bash,perl,ubuntu,renaming,Python,Bash,Perl,Ubuntu,Renaming,我有一个文件夹,其中包含名为image1.png、image2.png、image3.png等的.png图像 按照这个文件夹的组织方式,3个连续的图像表示来自同一主题的数据,因此我希望它们使用相同的识别号+一个字母来区分。像这样: image1.png --> 1-a.png image2.png --> 1-b.png image3.png --> 1-c.png image4.png --> 2-a.png image5.png --> 2-b.png imag

我有一个文件夹,其中包含名为
image1.png、image2.png、image3.png等的
.png
图像

按照这个文件夹的组织方式,3个连续的图像表示来自同一主题的数据,因此我希望它们使用相同的识别号+一个字母来区分。像这样:

image1.png --> 1-a.png
image2.png --> 1-b.png
image3.png --> 1-c.png
image4.png --> 2-a.png
image5.png --> 2-b.png
image6.png --> 2-c.png
等等

最好的方法是什么?一个
Perl
脚本?或者在
python
中生成具有所需名称的
.txt
,然后使用它重命名文件?我正在使用Ubuntu


提前谢谢

给定Python中的文件列表
文件
,您可以使用
itertools.product
生成所需的数字和字母对:

from itertools import product
import os

os.chdir(directory_containing_images)
# instead of hard-coding files you will actually want:
# files = os.listdir('.')
files = ['image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png', 'image6.png']
for file, (n, a) in zip(files, product(range(1, len(files) // 3 + 2), 'abc')):
    os.rename(file, '{}-{}.png'.format(n, a))
如果将
os.rename
替换为
print
,则上述代码将输出:

image1.png 1-a.png
image2.png 1-b.png
image3.png 1-c.png
image4.png 2-a.png
image5.png 2-b.png
image6.png 2-c.png

perl
中,您可以执行以下操作:

my @new_names = map {
    my ( $n ) = $_ =~ /image(\d+)\.png/;
    my $j = (($n - 1)  % 3) + 1;
    my $char = (qw(a b c))[ int( $n / 3 ) ];
    "$j-$char.png"
} @files;
这假定
@文件
数组没有特殊顺序。

趣味项目。:)


显然,根据需要编辑pathing&c。

我在python3中尝试了这一点,它可以根据您的需要工作

import os
import string
os.chdir(path_to_your_folder)
no=1
count=1
alphabet = ['a','b','c']
count=0
for filename in os.listdir(os.getcwd()):
    newfilename = (str(no) + "-" + alphabet[count]+".png")
    os.rename(filename,newfilename)
    count=(count+1)%3
    if count==0:
        no=no+1

几乎任何脚本语言都足够了。为什么不试一试,看看你的情况如何?脚本也应该处理排序逻辑,或者你可以让它按一定的顺序排序?因为我们不知道确切的文件名模式是什么。您在报告中提到了
image01
image1
question@Kent文件已排序,并且没有前导零。谢谢你指出这一点-我刚刚编辑了这个问题。我最终选择了这个解决方案。我不得不添加人工/自然排序来解决订单问题,比如
image1.png
后面跟着
image10.png
。这个问题有助于:
import os
import string
os.chdir(path_to_your_folder)
no=1
count=1
alphabet = ['a','b','c']
count=0
for filename in os.listdir(os.getcwd()):
    newfilename = (str(no) + "-" + alphabet[count]+".png")
    os.rename(filename,newfilename)
    count=(count+1)%3
    if count==0:
        no=no+1