Why use os.path.join over string concatenation?

user1905410 picture user1905410 · Dec 19, 2012 · Viewed 15.2k times · Source

I'm not able to see the bigger picture here I think; but basically I have no idea why you would use os.path.join instead of just normal string concatenation?

I have mainly used VBScript so I don't understand the point of this function.

Answer

user1902824 picture user1902824 · Dec 19, 2012

Portable

Write filepath manipulations once and it works across many different platforms, for free. The delimiting character is abstracted away, making your job easier.

Smart

You no longer need to worry if that directory path had a trailing slash or not. os.path.join will add it if it needs to.

Clear

Using os.path.join makes it obvious to other people reading your code that you are working with filepaths. People can quickly scan through the code and discover it's a filepath intrinsically. If you decide to construct it yourself, you will likely detract the reader from finding actual problems with your code: "Hmm, some string concats, a substitution. Is this a filepath or what? Gah! Why didn't he use os.path.join?" :)