I often have to join some pathes, bee it URLs or Filepaths.
For this there are some built ins like os.path.join or the urllib.join. The Problem is that they all have their own quirks in regard of what counts a relative etc, which can make sense but is a pain to clean up when user-generated input is relevant. For this I came up with this pretty simple function. I think it might be a nice addition to the lib in TD itself.
def path_join( *args ):
return ("/").join( [ arg.replace("\\", "/").strip("/") for arg in args])
This takes care of weird \, leading and trailing / so all elements get joined no matter the formatting.
I could put something like this in TDFunctions. Would that work for you or do you need it to be accessible without an import?
TDFunctions sounds pretty nice, thanks
I will also add it to my own pythonUtil, but I use this function so often that first setting my own utils up is a bother
Ah, I looked into this a bit but because of irregularities it is much safer for people (including you!) to use the standard Python libraries.
If you have specific struggles using these, let’s discuss here and figure out some best solutions.
Interrested about the irregularities!
I think there are two main issues I have with both solutions:
A /subfolder in a path will remove the leading folder.
so foo /bar becomes /bar.
They both use \ instead of /, which is stumpled uppon as generating an issue. os.path.join even mixxes them. Pathlib at least creates a single one.
I think the point where I use this much more is when working with URL as it will happen much more often that a URL is defined by trailing or leading /, resulting is some unexpected behaviour.
The struggle is that I have to sanitize the userInput when composing paths. So when I have o sanitize this anyway, then I can compose the path directly. This does specifically different behaviour then the built in module to make it more forgiving for user-input as the rules are not alway intuitive.
Ah yeah, I see. This is more than just joining paths, it’s as you say sanitizing user input. That sort of sanitization is beyond the scope of general TD Python utilities and the general consensus is that we don’t want people to start using homebrew utility functions for things the Python libraries do.
I do see the use in your function, and I appreciate that you make this stuff available to the community!
As far as irregularities, it mostly has to do with the cases where people might want backslashes and also where people might want whatever sort of separator the currently running OS is using. Too many exceptions.
Side note: I don’t like pathJoin(“/foo bar”) yielding “foo/bar”. That converts an absolute to a relative!
All valid points, I understand. I found myself using this function so often that I assumed it might be pretty streight forward, but going against built-in function and having so many edge cases makes it not as versitel as I assumed it to be. So, I rest my case