I made myself a function to check if a string is a path or an URL:
import os def isPath(s): """ @param s string containing a path or url @return True if it's a path, False if it's an url' """ if os.path.exists(s): # if a file with name s exists, we don't check any further and just return True return True elif s.startswith("/"): # clearly a path, urls never start with a slash return True elif "://" in s.split("."): # if a protocol is present, it's an url return False elif "localhost" in s: # special case for localhost domain name where splits on . would fail return False elif len(s.split("/").split(".")) > 1: # dots before the first slash, normally separating TLD and domain name return False elif len(s.split("/").split(":")) > 1: # if colons are present, either it's a IPv6 adress or there is a port number return False else: # all possible cases of an url checked, so it must be a path return True
Did I miss any cases of an url / path, and can the function be improved in some way ?
file:///path/to/fileis perfectly valid path, as is