示例数据:
D:\Movies\Iron Man\Iron Man.mp4
D:\Movies\Kung Fu Panda 3\Kung Fu Panda 3.mp4
D:\Movies\SING\SING.mp4
D:\Movies\Split\Split.mp4
D:\Movies\Zootopia\Zootopia.mp4
如何在迭代for
循环时在反斜杠之前修剪这些路径,以便我可以提取名称。即。
Iron Man.mp4
Kung Fu Panda 3.mp4
SING.mp4
Split.mp4
Zootopia.mp4
帮助你真的很有帮助。
答案 0 :(得分:0)
您需要使用os.path.basename()
和os.path.splitext()
的组合,如下所示:
import os
movie_filenames = [
r"D:\Movies\Iron Man\Iron Man.mp4",
r"D:\Movies\Kung Fu Panda 3\Kung Fu Panda 3.mp4",
r"D:\Movies\SING\SING.mp4",
r"D:\Movies\Split\Split.mp4",
r"D:\Movies\Zootopia\Zootopia.mp4",
]
for movie_filename in movie_filenames:
basename = os.path.basename(movie_filename)
movie_name = os.path.splitext(basename)[0]
print movie_name
第一个调用将从路径中提取文件名,第二个调用将从扩展名中分离出名称(您只需要名称,即[0]
)。这会给你:
Iron Man
Kung Fu Panda 3
SING
Split
Zootopia