113

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
user1905410
  • 1,161
  • 2
  • 7
  • 4
  • Also, [why you may want to use pathlib over os.path](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/) by now – danicotra May 16 '20 at 09:22

3 Answers3

115

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

Community
  • 1
  • 1
  • 4
    Thanks. The Smart and Clear parts are exactly the kind of reasoning I was looking for when asking that same question to myself: the portable part is easily attained by concatenation with "/" instead of windows-only "\" so it is kind of moot. – Léo Germond Jul 02 '16 at 11:12
  • 7
    point 3 has merit, but 1 and 2 are moot. / works on Windows. What OS are you ever using that doesn't support it? And double trailing slashes are normalised for you by the OS/FS. I'm not saying don't use `os.path.join`, but if you do, do it for the right reasons. There is a lot of cargo-culting around os.path.join. "A foolish consistency is the hobgoblin of little minds," as they say. – hraban May 03 '17 at 10:46
  • If the code is only for one specific OS, then there is no point in using `os.path.join`. – Shiplu Mokaddim Jan 27 '21 at 10:26
  • 1
    What about in terms of computation speed? – haneulkim May 13 '21 at 03:37
  • Very useful. I am also confused by this question recently. – johnwow Oct 19 '21 at 03:17
  • 2
    If you are simply joining a path to a file, you should use `path + '/' + file`. This is imminently readable *and* portable to all OS. Using `os.path.join` is hazardous because it is inconsistent. For example `os.path.join('/foo/bar','test')` will return `/foo/bar/test` on some systems and `/foo/bar\\test` on others. – John Henckel Mar 02 '22 at 15:49
  • @haneulkim Obviously simple concatenation is much faster compared to a function call. But that is so miniscule to care about; it’s unnecessary micro-optimization. – Константин Ван May 26 '22 at 18:35
  • They are not fully equivalent however. Consider `os.path.join('a', '/b')`, which actually returns `/b`. So if you're mixing these methods, or converting from string concatenation to `os.path.join`, make sure path components don't unexpectedly have a leading slash. – ketil Mar 24 '23 at 06:50
5

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 '\'

jassinm
  • 7,323
  • 3
  • 33
  • 42
  • 6
    Strangely enough, though, using `/` works on Windows, with CPython… – Eric O. Lebigot Dec 19 '12 at 01:51
  • 1
    This. Why would you try and handle path separators etc yourself when there is a function designed to do it for you? – Blair Dec 19 '12 at 01:51
  • 1
    I read the comments and it joins paths together, i just cannot see why I would ever use it, apologies as like i said I'm clearly not seeing the bigger picture. – user1905410 Dec 19 '12 at 01:52
  • @user1905410 It does more than that, as the Fine Documentation covers. –  Dec 19 '12 at 01:57
  • @user1905410 It does more than that, as the Fine Documentation coveres. –  Dec 19 '12 at 01:57
  • @user1905410: No, but [the documentation](http://docs.python.org/2/library/os.path.html#os.path.join) gives you more reasons. There are many use cases, but people often use it to not address path concatenation in more complex way, plus allow you to use the same code for both relative (eg. `os.path.join('/home', 'tadeck')`) and absolute paths (eg. `os.path.join('/home', '/usr')`). – Tadeck Dec 19 '12 at 01:59
-2

It is OS-independent. If you hardcode your paths as C:\Whatever they will only work on Windows. If you hardcode them with the Unix standard "/" they will only work on Unix. os.path.join detects the operating system it is running under and joins the paths using the correct symbol.

bkaiser
  • 647
  • 8
  • 22
  • 12
    ```If you hardcode them with the Unix standard "/" they will only work on Unix.``` That is wrong. "/" works just fine on windows AND linux/unix/bsd/darwin. – Léo Germond Jul 02 '16 at 11:18