11

I am trying to figure out if it is better to use:

os.path.join(str1, str2)

or:

str1 + os.sep + str2

Profiling with timeit I found that, as expected, concatenation is faster:

%timeit 'playground' + os.sep + 'Text'
10000000 loops, best of 3: 139 ns per loop

%timeit os.path.join('playground', 'Text')
1000000 loops, best of 3: 830 ns per loop

So my question is, since concatenation is also shorter, is there a reason to use os.path.join(()?

Thanks

2 Answers 2

24

It's right there in the documentation:

os.path.join(path1[, path2[, ...]])

Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

os.path.join does much more:

>>> os.path.join("/home/", "/home/foo")
'/home/foo'
>>> "/home/" + os.sep + "/home/foo"
'/home///home/foo'

You will never have a situation where os.path.join is the bottleneck of your program, so use it, it's much more readable too.

Sign up to request clarification or add additional context in comments.

1 Comment

I would not recommend using it, when you know, you don't need it. The result of os.path.join is less predictable, and introducing overhead for absolutely nothing is not "premature optimization" but just bad coding style. It is not a bottleneck but the cumulation of such decisions is, what makes modern computers slow. If, for example, you have a path you got from os.path.realpath and a filename of which you know that it contains no slashes, os.sep.join is the better choice, as it is in most situations.
7

os.path.join takes multiple arguments:

import os
os.path.join('a', 'b', 'c')

This will become rather long with concatenation for many path parts.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.