Skip to content

Instantly share code, notes, and snippets.

@chadgroom
Last active December 17, 2020 20:54
Show Gist options
  • Save chadgroom/e1308721eaaa46efbd056cea8f676057 to your computer and use it in GitHub Desktop.
Save chadgroom/e1308721eaaa46efbd056cea8f676057 to your computer and use it in GitHub Desktop.
A simple utility that parses any given path string then returns a helpful object with cross-platform path representations.
#!/usr/bin/env python3
# PARSES ANY GIVEN PATH AND RETURNS AN OBJECT WITH CROSS-PLATFORM PATH REPRESENTATIONS
def safePathParser(string):
base = None
dir_ = None
if "\\" in string and "/" not in string:
exp = string.split("\\")
base = exp[len(exp) - 1]
del exp[len(exp) - 1]
dir_ = "\\".join(exp)
return {
"basename": base,
"dir": dir_,
"nt": string,
"unix": string.replace("\\", "/")
}
if "\\" in string and "/" in string:
dir_ = string.split("/")[0]
base = string.split("/")[1]
return {
"basename": string.split("/")[1],
"dir": string.split("/")[0],
"nt": string.replace("/", "\\"),
"unix": string.replace("\\", "/")
}
if "/" in string and "\\" not in string:
exp = string.split("/")
base = exp[len(exp) - 1]
del exp[len(exp) - 1]
dir_ = "/".join(exp)
return {
"basename": base,
"dir": dir_,
"nt": string.replace("/", "\\"),
"unix": string
}
# PARSE A WINDOWS NATIVE PATH
path = "C:\\Users\\TestUser\\test.exe"
parsedPath = safePathParser(path)
print(parsedPath)
print("Basename: %s" % (parsedPath['basename'],))
print("Native Directory: %s" % (parsedPath['dir'],))
print("Full path for Windows: %s" % (parsedPath['nt'],))
print("Full path for Unix: %s" % (parsedPath['unix'],))
# LOAD THE UNIX CONVERSION AS A NEW OBJECT
unixConversion = safePathParser(parsedPath['unix'])
print("Unix Basename (same): %s" % (unixConversion['basename'],))
print("Unix Directory: %s" % (unixConversion['dir'],))
print("Reverse conversion back to Windows: %s" % (unixConversion['nt'],))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment