按数字顺序+字母重命名文件

时间:2019-03-06 13:22:04

标签: python bash perl ubuntu renaming

我有一个文件夹,其中包含名为.png等的image1.png, image2.png, image3.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脚本?或在.txt中使用所需名称生成python,然后使用它来重命名文件?我正在使用Ubuntu

谢谢!

4 个答案:

答案 0 :(得分:1)

鉴于Python中的文件列表files,您可以使用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

答案 1 :(得分:0)

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;

这假设@files数组没有特殊顺序。

答案 2 :(得分:0)

有趣的项目。 :)

declare -i ctr=1 fileset=1              # tracking numbers
declare -a tag=( c a b )                # lookup table
for f in $( printf "%s\n" *.png |       # stack as lines
            sort -k1.6n )               # order appropriately
do ref=$(( ctr++ % 3 ))                 # index the lookup
   end=${f##*.}                         # keep the file ending
   mv "$f" "$fileset-${tag[ref]}.$end"  # mv old file to new name
   (( ref )) || (( fileset++ ))         # increment the *set*
done

mv image1.png 1-a.png
mv image2.png 1-b.png
mv image3.png 1-c.png
mv image4.png 2-a.png
mv image5.png 2-b.png
mv image6.png 2-c.png
mv image7.png 3-a.png
mv image8.png 3-b.png
mv image9.png 3-c.png
mv image10.png 4-a.png
mv image11.png 4-b.png
mv image12.png 4-c.png

很明显,根据需要编辑&c。

答案 3 :(得分:0)

我在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