0

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?

6
  • 5
    Why not just use os.path.basename() to get the filename? Commented Jan 31, 2022 at 23:39
  • 5
    Are you saying in a complicated way that you want the base file name? os.path.basename(s) is designed for that task. Commented Jan 31, 2022 at 23:39
  • You could do something like ``` import os s = '/Users/cobyk/Downloads/GrassyPath.jpg' print(os.path.basename(s)) ``` Note: tested this on a mac so the slashes are the wrong direction for you, but it you put in your file path on windows it should work the same. Commented Jan 31, 2022 at 23:46
  • It is a little known fact that ALL Windows APIs accept either forward slashes or backward slashes. It's only the command shell that insists on backslashes. Commented Jan 31, 2022 at 23:58
  • 1
    os.path is sooo ancient, for new code I highly recommend using the pathlib module that was added in Python 3.4 (which was released 2014-03-16). Commented Feb 1, 2022 at 0:21

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.