我经常发现自己的情况是我有一个文件夹,其中包含根据某个文件命名约定命名的文件,我必须手动完成它们才能将它们重命名为我想要的文件。这是一项费力的重复性任务。
E.g。 01_artist_name_-_album_title_-_song_title_somethingelse.mp3
- > Song_Title.mp3
因此删除某些信息,用空格替换下划线和大写。不仅仅是音乐,这只是一个例子。
我一直在考虑使用Python自动执行此任务。基本上我希望能够输入起始约定和我想要的约定,并相应地重命名它们。
理想情况下,我希望能够在Windows上使用Python进行此操作,但如果在bash(或UNIX上的Python)中更容易实现,我可以使用Ubuntu机器。
如果有人能够解释我如何解决这个问题(建议使用IO python命令读取文件夹的内容 - 并重命名文件 - 在Windows上,以及我如何从文件名中剥离信息并对其进行分类,也许使用RegEx?)我会看到我能做什么并随着进度更新。
答案 0 :(得分:1)
针对您的特殊情况:
import glob, shutil, os.path
# glob.glob returns a list with all pathes according to the given pattern
for path in glob.glob("music_folder/*.mp3"):
# os.path.dirname gives the directory name, here it is "music_folder"
dirname = os.path.dirname(path)
# example: 01_artist_name_-_album_title_-_song_title_somethingelse.mp3
# split returns "_song_title_somethingelse.mp3"
interesting = path.split("-")[2]
# titlepart is a list with ["song", "title"], the beginning "_" and the
# 'somehting' string is removed by choosing the slice 1:-1
titlepart = interesting.split("_")[1:-1]
# capitalize converts song -> Song, title -> title
# join gluest both to "Song_Title"
new_name = "_".join(p.capitalize() for p in titlepart)+".mp3"
# shutil.move renames the given file
shutil.move(path, os.path.join(dirname, new_name))
如果要使用正则表达式,则必须替换:
m=re.search(".*-_(\S+_\S+)_.*",path)
if m is None:
raise Exception("file name does not match regular expression")
song_name = m.groups()[0]
titlepart = song_name.split("_")