os.path.join() or os.sep.join()?

Posted on July 23, 2019

There are two functions join a full path. E.g.: In drive: C:

|- test
|   |- test.xt
  • os.path.join

    import os
    fullpath = os.path.join('c:', 'test', 'test.txt')

    Output on windows:

    c:test\test.txt

    Output on Mac OS

    c:/test/test.txt

  • os.sep.join

    import os
    fullpath = os.sep.join(['c:', 'test', 'test.txt'])

    Output on windows:

    c:\test\test.txt

    Output on Mac OS

    c:/test/test.txt

From the outputs, you can see the difference: os.path.join() doesn’t work as expected on windows.

Further verification:

with open(fullpath) as test:
    test.read()

Run with error:

    with open(fullpath) as test:
FileNotFoundError: [Errno 2] No such file or directory: 'c:test\\test.txt'

Conclusion:

Though os.sep.path might has other beneficial: Join one or more path intelligentyly

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

but, be careful when using it on windows.


os.path.join() or os.sep.join()?


donation

Scan the QR code using WeChat

comments powered by Disqus