python - 使用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 和正则表达式的新手。任何帮助将不胜感激。谢谢
解决方案
使用带有符号组名的正则表达式将允许您轻松访问要操作的文件名部分。我使用了一个类,因为我认为您可能希望在重命名过程中添加其他功能,例如子级别或最低级别。
#!/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)
推荐阅读
- javascript - 在threejs中使用toneMapping时如何避免背景图像由白色变为灰色?
- flutter - 在 Flutter 中将文件保存到下载时出错
- python - 使用 python、pandas 合并 2 个基于 3 个条件的单独 excel 文件
- java - 两个字符串var之间带有+运算符的java错误语句
- python - 语音识别并没有证明我有不同俚语英语的全文
- xml - ISO20022 消息模式节点搜索指定路径
- list - 运行此序言代码时显示错误
- javascript - mongoose 与数据库的连接代码不起作用。=> mongoose.connection.once()
- c++ - 有人可以解释为什么我的功能“超出范围”吗?
- python - django-admin 无法创建项目,因为 - zsh: /usr/local/bin/django-admin: bad interpreter