-2

Sample Data :

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

How can I trim these paths just before the backslash while iterating through a for loop, so that I can extract the names. i.e.

Iron Man.mp4
Kung Fu Panda 3.mp4
SING.mp4
Split.mp4
Zootopia.mp4

It will be really helpful of you to help.

KodeRex
  • 9
  • 5

1 Answers1

0

You need to use a combination of os.path.basename() and os.path.splitext() as follows:

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)

The first call will extract the filename from the path, and the second call with split out the name from the extension (you only want the name, thus the [0]). This would give you:

Iron Man
Kung Fu Panda 3
SING
Split
Zootopia
Martin Evans
  • 45,791
  • 17
  • 81
  • 97