Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use os.path.join over string concatenation?

People also ask

Why should you use os path join?

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.

Does os path join return a string?

os. path. join returns a string; calling the join method of that calls the regular string join method, which is entirely unrelated.

Is Join faster than concatenation Python?

String join is significantly faster then concatenation. Why? Strings are immutable and can't be changed in place. To alter one, a new representation needs to be created (a concatenation of the two).

What is os path?

The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats.


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?" :)


Will work on Windows with '\' and Unix (including Mac OS X) with '/'.

for posixpath here's the straightforward code

In [22]: os.path.join??
Type:       function
String Form:<function join at 0x107c28ed8>
File:       /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
Definition: os.path.join(a, *p)
Source:
def join(a, *p):
    """Join two or more pathname components, inserting '/' as needed.
    If any component is an absolute path, all previous path components
    will be discarded."""
    path = a
    for b in p:
        if b.startswith('/'):
            path = b
        elif path == '' or path.endswith('/'):
            path +=  b
        else:
            path += '/' + b
    return path

don't have windows but the same should be there with '\'