How to safely get the file extension from a URL?

Use urlparse to parse the path out of the URL, then os.path.splitext to get the extension.

import os
try:
    import urlparse
except ImportError:
    from urllib.parse import urlparse

url="http://www.plssomeotherurl.com/station.pls?id=111"
path = urlparse.urlparse(url).path
ext = os.path.splitext(path)[1]

Note that the extension may not be a reliable indicator of the type of the file. The HTTP Content-Type header may be better.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)