Python code to extract the file name from path or URL is explained below.
- Find the delimiter “/” position before the file name using firstpos=path.rfind(“/”)
- Find the last position of the file name using lastpos=len(path)
- 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:
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])
Output: File name without extension
Also see Extract all links from webpage using python selenium webdriver