首页 > 解决方案 > 使用python重命名多个文件

问题描述

我想从以下文件重命名

l4_0_0.m4a
l4_0_1.m4a
l4_0_2.m4a
l5_0_0.m4a
l5_0_1.m4a
l5_0_2.m4a
l6_0_0.m4a
.
.
.
l11_0_2.m4a

给以下名字

l5_0_0.m4a
l5_0_1.m4a
l5_0_2.m4a
l6_0_0.m4a
l6_0_1.m4a
l6_0_2.m4a
l7_0_0.m4a
.
.
.
l12_0_2.m4a

我正在开发一个曾经有 12 个级别的应用程序,我必须在 5 级之前添加一个级别(l4_ _)因此,我必须在 5 级之后重命名所有级别。5 级 (l4_ _ ) 将变为 6 级 (l5_ _ )

我是 python 和正则表达式的新手。任何帮助将不胜感激。谢谢

标签: pythonregexfilerename

解决方案


使用带有符号组名的正则表达式将允许您轻松访问要操作的文件名部分。我使用了一个类,因为我认为您可能希望在重命名过程中添加其他功能,例如子级别或最低级别。

#!/usr/bin/env python3

import re
import os


class NamedFile(object):
    file_mask = re.compile(r"(?P<PREFIX>l)(?P<LEVEL>\d+)_(?P<SUBLEVEL>\d+)_(?P<LOWLEVEL>\d+)\.(?P<EXTENSION>m4a)")
    file_format = "{PREFIX}{LEVEL}_{SUBLEVEL}_{LOWLEVEL}.{EXTENSION}".format

    @classmethod
    def files(cls, path):
        for f in sorted(os.listdir(path)):
            groups = cls.file_mask.match(f)
            if groups is not None:
                yield (path, f, groups.groupdict())

    @classmethod
    def new_name(cls, groups, increment):
        level = int(groups["LEVEL"]) + 1
        groups["LEVEL"] = level
        return cls.file_format(**groups)

    @classmethod
    def rename(cls, path, increment):
        for path, f, file_parts in NamedFile.files(path):
            new_filename = cls.new_name(file_parts, increment)
            abs_new = os.path.join(path, new_filename)
            abs_old = os.path.join(path, f)
            os.rename(abs_old, abs_new)


if __name__ == "__main__":
    print("===Original file names===")
    for path, f, file_parts in NamedFile.files("."):
        print(f)

    NamedFile.rename(".", 1)

    print("===New file names===")
    for path, f, file_parts in NamedFile.files("."):
        print(f)

推荐阅读