整理音乐文件时,临时遇到需要批量修改文件名,就应用Python来完成了。
# 批量修改文件名的一部分
- 识别就文件名中需要替换的字符,并替换成新字符,输出新文件名。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import os
def rename\_files\_in\_folder(folder\_path, old\_string, new\_string): """ 批量修改文件名中的一部分字符串。
:param folder\_path: 文件夹路径 :param old\_string: 需要被替换的字符串 :param new\_string: 新的字符串,用于替换旧字符串 """ for filename in os.listdir(folder\_path): if old\_string in filename: os.rename(os.path.join(folder\_path, filename), os.path.join(folder\_path, filename.replace(old\_string, new\_string)))
folder = "/Volumes/music/韩红最-令人感动的专辑《醒了》" old\_str = "mp3" new\_str = ".mp3" rename\_files\_in\_folder(folder, old\_str, new\_str)
|
- 识别旧文件名中的数字序号并删除,输出不含序号的新文件名。
1 2 3 4 5 6 7 8 9 10 11 12 13
| import os import re
def remove\_numbers\_from\_file\_names(directory): for filename in os.listdir(directory): if re.match(r'\d+', filename): number\_pattern = re.compile(r'^\d+') new\_filename = re.sub(number\_pattern, '', filename) os.rename(os.path.join(directory, filename), os.path.join(directory, new\_filename))
directory\_path = '/Volumes/music/韩红最-令人感动的专辑《醒了》' remove\_numbers\_from\_file\_names(directory\_path)
|