Reputation: 503
URL
http://www.example.com
www.example.com
http://example.com
https://example.com
LOCAL FILES
file:///example.html
/home/user/example.html
./home/user/example.html
.dir/data/example.html
Consider above input and identify whether given input string is local regular file or a URL?
What i have Tried
import os
from urllib.parse import urlparse
def is_local(_str):
if os.path.exists(path1):
return True
elif urlparse(_str).scheme in ['','file']:
return True
return False
Call
is_local('file:///example.html') # True
is_local('/home/user/example.html') # True
is_local('./home/user/example.html') # True
is_local('.dir/data/example.html') # True
is_local('http://www.example.com') # False
is_local('www.example.com') # True
is_local('http://example.com') # False
is_local('https://example.com') # False
Is there any pythonic way to identify a file is local or an URL without using urllib?
Upvotes: 2
Views: 2480
Reputation: 57033
You can use a combination of urllib.parse.urlpath
and os.path.exists
. The first extracts a file path from the URL, whilst the second checks if the path actually refers to a file.
from urllib.parse import urlparse
from os.path import exists
def is_local(url):
url_parsed = urlparse(url)
if url_parsed.scheme in ('file', ''): # Possibly a local file
return exists(url_parsed.path)
return False
Upvotes: 7