首页 > 解决方案 > 如何使用 Python 在文件夹名称中测试是否存在年份,但没有括号

问题描述

我的电影收藏存储在这样的文件夹中:

D:\Movies\Batman (2000)\Batman.mp4
D:\Movies\Superman (2001)\Superman.mp4
D:\Movies\Wonder Woman 2002\Wonder Woman.mp4

我的大多数电影的文件夹名称中都有年份,并用圆括号括起来,即“(”和“)”。

然而,我的一些电影在文件夹名称中有年份但没有括号,请参见例如 Wonder Woman 2002 文件夹。

我知道如何使用 os.walk 遍历所有文件夹名称。

如何扫描是否存在包含该年份没有括号的年份的文件夹,然后重命名文件夹以包含括号?

标签: python-3.x

解决方案


干得好:

import os

file_list = os.listdir()
for each in file_list:
    if not "(" in each:
        # Finds the index of the last space in 
        last_space_idx = each.rfind(" ")

        # Also check if there is a space somewhere in the file.
        # If so, rename it to the below format.
        if last_space_idx != -1:
            os.rename(each, "%s (%s)" % (each[:last_space_idx], each[last_space_idx + 1:]))

这是一个非常简单的检查器,它只是确认文件夹名称中是否有(任何地方。我不想放太多的条件,因为它会降低程序的速度,但可以很容易地添加更多的条件。此外,该文件夹似乎只有电影名称,因此您应该几乎没有边缘情况。如果您有任何问题或想要添加更多限制,请告诉我。


推荐阅读