Both ways work:

os.path.join(os.path.dirname(__file__), '../../../testdata'))


os.path.join(os.path.dirname(__file__), '..', '..', '..', 'testdata'))

First is shorter. Is there any reason to use 2nd syntax?


The only noticeable difference is that in the second example you let the os library take care of choosing the directory separator. This can be useful to prevent conflicts between different operating systems, though this shouldn't usually be a problem.

I would vote for the second option.

  • \$\begingroup\$ Python will resolve / as path separator on all systems (including Windows). For that reason, I always use /, and also define a normjoin helper function to keep everything straight for me: def normjoin(*p): return os.path.normpath(os.path.join(*p)) \$\endgroup\$ – scottbb Jun 2 '16 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.