如何在 Python 中循环文件并重命名它们
我有一个音乐目录,其中包含专辑文件夹以及每个级别的单独歌曲。我如何遍历所有这些也以不同格式(mp3、wav 等)编码的文件?此外,有没有一种方法可以使用正则表达式将它们重命名为更符合我喜欢的格式?
谢谢
I have a directory of music that has album folders as well as individual songs on each level. How can I traverse all of these files that also are encoded in different formats(mp3, wav etc)? In addition is there a way I can rename them to a format that is more consistent to my liking using regular expressions?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
os.walk
遍历目录及其子目录中的文件,递归os.rename
重命名它们我认为,文件的编码在这里不起作用。当然,您可以检测它们的扩展名(使用 os.path.splitext 来实现)并基于它执行某些操作,但只要您只需要重命名文件(即操作它们的名称),内容几乎不重要。
os.walk
to go over files in the directory and its sub-directories, recursivelyos.rename
to rename themThe encoding of the files pays no role here, I think. You can, of course, detect their extension (use
os.path.splitext
for that) and do something based on it, but as long as you just need to rename files (i.e. manipulate their names), contents hardly matter.我在我编写的程序中使用了这段代码。我用它来获取图像文件的递归列表,调用模式类似于
re.compile(r'\.(bmp|jpg|png)$', re.IGNORECASE)
。我想你明白了。获得列表后,应用重命名规则就很容易了。
os.rename
是你的朋友,请参阅http://docs.python。 org/library/os.html。I use this piece of code in a program I wrote. I use it to get a recursive list of image files, the call pattern is something like
re.compile(r'\.(bmp|jpg|png)$', re.IGNORECASE)
. I think you get the idea.After you have the list, it would be easy to apply a renaming rule.
os.rename
is your friend, see http://docs.python.org/library/os.html.