Python: Extract file name from URL path [with and without extension]

Python code to extract the file name from path or URL is explained below.

  1. Find the delimiter “/” position before the file name using   firstpos=path.rfind(“/”)
  2. Find the last position of the file name using lastpos=len(path)
  3. Extract the file name using path[firstpos+1:lastpos]. Add 1 to the first position to avoid extracting the delimeter “/”.

Python code to get file name from URL

path="https://gethowstuff.com/wp-content/uploads/2017/02/python-extract-string-output-on-powershell.jpg"
firstpos=path.rfind("/")
lastpos=len(path)
print(path[firstpos+1:lastpos])

Output:

python-code-extract-file-name-url-path

Output: File Name with extension

Get file name from URL without extension

Below is the code if you want to extract the file name from URL or path without extension (example .jpg).

path="https://gethowstuff.com/wp-content/uploads/2017/02/python-extract-string-output-on-powershell.jpg"
firstpos=path.rfind("/")
lastpos=path.rfind(".")
print(path[firstpos+1:lastpos])
python-extract-file-name-without-extension

Output: File name without extension

Also see Extract all links from webpage using python selenium webdriver

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published. Required fields are marked *