python-3.x - 如何使用 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 遍历所有文件夹名称。
如何扫描是否存在包含该年份没有括号的年份的文件夹,然后重命名文件夹以包含括号?
解决方案
干得好:
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:]))
这是一个非常简单的检查器,它只是确认文件夹名称中是否有(
任何地方。我不想放太多的条件,因为它会降低程序的速度,但可以很容易地添加更多的条件。此外,该文件夹似乎只有电影名称,因此您应该几乎没有边缘情况。如果您有任何问题或想要添加更多限制,请告诉我。
推荐阅读
- android - 在使用对讲时通过滑动在标题之间导航
- r - 输出矩阵中每一列的第一个元素的行索引以满足逻辑条件
- python - 将 SQLAlchemy scoped_session 与 Celery 一起使用
- reactjs - 模态不使用 React 路由器和链接关闭
- css - 具有特定属性的后代元素的 css 选择器。
- objective-c - macOS 获取系统中创建连接的通知
- url - PHP中的GET url数据限制
- azure - 如何在 Sprint 中添加任务、问题和错误
- java - 在 Android Studio 中隐藏私人信息的最佳方法是什么?
- c++ - 如何使用 CMake 为其他项目“安装”和使用内部依赖项