如何重命名具有相同字符串的文件并添加后缀

我在文件名中具有相同字符串的子目录中有很多图像,我想重命名这些文件并在它们的名称后附加一个后缀。

例子:

1/AB2011-BLUE-BW.jpg
1/AB2011-WHITE-BW.jpg
1/AB2011-BEIGE-BW.jpg
2/AB2011-WHITE-2-BW.jpg
2/AB2011-BEIGE-2-BW.jpg
1/AB2012-BLUE-BW.jpg
1/AB2012-WHITE-BW.jpg
1/AB2012-BEIGE-BW.jpg
...

我想重命名这个文件

1/AB2011-01.jpg
1/AB2011-02.jpg
1/AB2011-03.jpg
2/AB2011-04.jpg
2/AB2011-05.jpg
1/AB2012-01.jpg
1/AB2012-02.jpg
1/AB2012-03.jpg
...

如何在 bash 或 python 中执行此操作?哪个图像得到 01,02,03 无关紧要。

stack overflow How to rename files with same string and add suffix
原文答案
author avatar

接受的答案

希望我能正确理解你想要什么。但是下面是如何做到这一点。

# importing os module
import os

# Function to rename multiple files
def main():

    folder = "1"

    # Keeps track of count of file name based on first field 
    fileNameCountDic = {}

    for count, filename in enumerate(os.listdir(folder)):

        # Original path to file
        src = f"{folder}/{filename}"  # foldername/filename, if .py file is outside folder

        # Get first field in file name so "B2011-BLUE-BW.jpg" -> "B2011"
        firstFileNameField = filename.split("-")[0]

        # If first field in filename is not in dic set it to be the first one
        if firstFileNameField not in fileNameCountDic:
          fileNameCountDic[firstFileNameField]=1
        else: # Else inc the count
          fileNameCountDic[firstFileNameField]+=1

        # Turn file count number to String
        fileNumber = str(fileNameCountDic[firstFileNameField])
        if len(fileNumber)==1: # Add space if one digit
          fileNumber=" "+fileNumber

        # Set the new path of the file
        dst = f"{folder}/{firstFileNameField}-{fileNumber}.jpg"

        # rename() function will
        # rename all the files
        os.rename(src, dst)

main()

答案:

作者头像

这是重命名逻辑的另一种实现。

from collections import defaultdict
from pathlib import Path
from typing import Iterable, Iterator

FILES = [
    '1/AB2011-BLUE-BW.jpg',
    '1/AB2011-WHITE-BW.jpg',
    '1/AB2011-BEIGE-BW.jpg',
    '2/AB2011-WHITE-2-BW.jpg',
    '2/AB2011-BEIGE-2-BW.jpg',
    '1/AB2012-BLUE-BW.jpg',
    '1/AB2012-WHITE-BW.jpg',
    '1/AB2012-BEIGE-BW.jpg'
]

def rename(files: Iterable[Path]) -> Iterator[tuple[Path, Path]]:
    """Rename a file according to the given scheme."""

    counter = defaultdict(int)

    for file in files:
        name, _ = file.stem.split('-', maxsplit=1)
        counter[name] += 1
        infix = str(counter[name]).zfill(2)
        yield file, file.parent / f'{name}-{infix}{file.suffix}'

def main() -> None:
    """Rename files."""

    for old, new in rename(map(Path, FILES)):
        print(old, '->', new)

if __name__ == '__main__':
    main()

您可以使用例如 glob 将其应用于实际文件系统:

from pathlib import Path

GLOB = '*/*.jpg'

def main() -> None:
    """Rename files."""

    for old, new in rename(Path.cwd().glob(GLOB)):
        old.rename(new)

if __name__ == '__main__':
    main()