Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Getting Filename from Long Path

Tags:

python

path

I have long paths to files like:

D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv

What is the best way to get just the file name from there, so I end up with:

Alexis Jordan - Good Girl

From there I want to cut the Artist and Title into separate parts, but I can manage that :)

like image 690
hshah Avatar asked Feb 24 '26 01:02

hshah


1 Answers

First you need to decode the URL encoding with urllib.unquote() then use the os.path module to split out the filename and extension:

import os
import urllib

path = urllib.unquote(path)
filename = os.path.splitext(os.path.basename(path))[0]

where os.path.basename() removes the directory path, and os.path.splitext() gives you a filename and extension tuple.

This then gives you the filename:

>>> import os
>>> import urllib
>>> path = 'D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv'
>>> path = urllib.unquote(path)
>>> path
'D:\\Media\\Music Videos\\Alexis Jordan - Good Girl.mkv'
>>> filename = os.path.splitext(os.path.basename(path))[0]
>>> filename
'Alexis Jordan - Good Girl'
like image 139
Martijn Pieters Avatar answered Feb 25 '26 15:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!