如何在 Python 中循环文件并重命名它们

发布于 2024-12-12 10:10:08 字数 116 浏览 6 评论 0原文

我有一个音乐目录,其中包含专辑文件夹以及每个级别的单独歌曲。我如何遍历所有这些也以不同格式(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

左秋 2024-12-19 10:10:09
  • os.walk 遍历目录及其子目录中的文件,递归
  • os.rename 重命名它们

我认为,文件的编码在这里不起作用。当然,您可以检测它们的扩展名(使用 os.path.splitext 来实现)并基于它执行某些操作,但只要您只需要重命名文件(即操作它们的名称),内容几乎不重要。

  • os.walk to go over files in the directory and its sub-directories, recursively
  • os.rename to rename them

The 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.

命硬 2024-12-19 10:10:09

我在我编写的程序中使用了这段代码。我用它来获取图像文件的递归列表,调用模式类似于 re.compile(r'\.(bmp|jpg|png)$', re.IGNORECASE)。我想你明白了。

def getFiles(dirname, suffixPattern=None):
        dirname=os.path.normpath(dirname)

        retDirs, retFiles=[], []
        for root, dirs, files in os.walk(dirname):
                for i in dirs:
                        retDirs.append(os.path.join(root, i))
                for i in files:
                        if suffixPattern is None or \
                           suffixPattern.search(i) is not None:
                                retFiles.append((root, i))

        return (retDirs, retFiles)

获得列表后,应用重命名规则就很容易了。 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.

def getFiles(dirname, suffixPattern=None):
        dirname=os.path.normpath(dirname)

        retDirs, retFiles=[], []
        for root, dirs, files in os.walk(dirname):
                for i in dirs:
                        retDirs.append(os.path.join(root, i))
                for i in files:
                        if suffixPattern is None or \
                           suffixPattern.search(i) is not None:
                                retFiles.append((root, i))

        return (retDirs, retFiles)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文