Kobayashi
Kobayashi

Reputation: 23

How to pull a substring off a string without knowing what the string is (file path)

I have a given file path. For example, "C:\Users\cobyk\Downloads\GrassyPath.jpg". I would like to pull in a separate string, the image file name.

I'm assuming the best way to do that is to start from the back end of the string, find the final slash and then take the characters following that slash. Is there a method to do this already or will I have search through the string via a for loop, find the last slash myself, and then do the transferring manually?

Upvotes: 0

Views: 62

Answers (2)

Daniel Walker
Daniel Walker

Reputation: 6782

You can certainly search manually as you've suggested. However, the Python standard library already has, as you suspected, a function which does this for you.

import os

file_name = os.path.basename(r'C:\Users\cobyk\Downloads\GrassyPath.jpg')

Upvotes: 0

martineau
martineau

Reputation: 123531

The pathlib module makes it very easy to access individual parts of a file path like the final path component:

from pathlib import Path

image_path = Path(r"C:\Users\cobyk\Downloads\GrassyPath.jpg")
print(image_path.name)  # -> GrassyPath.jpg

Upvotes: 1

Related Questions